class MyClass:
var1 = 1
def update(value):
MyClass.var1 += value
def __init__(self,value):
self.value = value
MyClass.update(value)
a = MyClass(1)
我试图在方法(init/strong>中更新类变量(var1),但我给出了:
TypeError: unbound method update() must be called with MyClass instance as first argument (got int instance instead)
我这样做是因为我希望通过调用print MyClass.var1来轻松访问类中的所有变量
您需要使用
@classmethod
装饰器:您混淆了类和实例。
MyClass
是一个类,a
是该类的实例。这里的错误是update
是一个实例方法。要从__init__
调用它,请使用:或者
或者,使
update
a类方法:相关问题 更多 >
编程相关推荐