Python调用classmethod未执行仅返回绑定方法该如何解决?
Python classmethod 代码修改方案
你当前的代码存在3处需要修正的点:
@classmethod修饰的类方法,必须默认接收第一个参数,行业约定命名为cls,指代当前类本身- 类属性
a不能直接在方法内通过变量名a访问,需要通过cls参数调用 - 调用类方法时末尾缺少括号
(),原写法仅获取方法对象本身,不会执行方法内的打印逻辑
修改后的可运行代码如下:
class Test: a = 'inside method' @classmethod def testclass_method(cls): print(cls.a) # 调用类方法 Test.testclass_method()
运行上述代码即可正常输出inside method。
内容的提问来源于stack exchange,提问作者Victor
相关产品推荐
相关产品推荐

