Updating Class variable within a instance method

落花浮王杯 提交于 2019-12-05 01:12:31

You are confusing classes and instances.

class MyClass(object):
    pass

a = MyClass()

MyClassis a class, a is an instance of that class. Your error here is that update is an instance method. To call it from __init__, use either:

self.update(value)

or

MyClass.update(self, value)

Alternatively, make update a class method:

@classmethod
def update(cls, value):
    cls.var1 += value

You need to use the @classmethod decorator:

$ cat t.py 
class MyClass:
    var1 = 1

    @classmethod
    def update(cls, value):
        cls.var1 += value

    def __init__(self,value):
        self.value = value
        self.update(value)

a = MyClass(1)
print MyClass.var1
$ python t.py 
2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!