class MyClass:
var1 = 1
def update(value):
MyClass.var1 += value
def __init__(self,value):
self.value = value
MyClass.update(value)
a = MyClass(1)
我正在尝试在方法(_init_)中更新类变量(var1),但我给了我:
TypeError: unbound method update() must be called with MyClass instance as first argument (got int instance instead)
我这样做是因为我想通过调用 print MyClass.var1 轻松访问类中的所有变量
最佳答案
你混淆了类和实例。
class MyClass(object):
pass
a = MyClass()
MyClass
是一个类,a
是该类的一个实例。您的错误是 update
是一个实例方法。要从 __init__
调用它,请使用:
self.update(value)
或
MyClass.update(self, value)
或者,使 update
成为一个类方法:
@classmethod
def update(cls, value):
cls.var1 += value
关于python - 在实例方法中更新类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923411/