python - 在实例方法中更新类变量

标签 python class methods instance

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/

相关文章:

Python 父子特定类结构

javascript - 使用 JavaScript 方法

c# - 使用参数从 JavaScript 调用 C# 方法

python - 如何修复 ImportError : cannot import name 'Event' in Dash from plotly (python)?

python - 如何从字典中创建一个句子

python - 为什么 Python 的无穷大哈希有 π 的数字?

javascript - 单击时交换类别

javascript,多态 new Myclass()?

python - 以编程方式将模块/函数集转换为 Python 类

python - 检查列表中的每个值是否存在于单个查询中给定的 Django 模型表中