Skip to content Skip to sidebar Skip to footer

Updating Class Variable Within A Instance Method

class MyClass: var1 = 1 def update(value): MyClass.var1 += value def __init__(self,value): self.value = value MyClass.update(value) a = MyCla

Solution 1:

You are confusing classes and instances.

classMyClass(object):
    pass

a = MyClass()

MyClass is 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:

@classmethoddefupdate(cls, value):
    cls.var1 += value

Solution 2:

You need to use the @classmethod decorator:

$ cat t.py 
classMyClass:
    var1 = 1@classmethoddefupdate(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

Post a Comment for "Updating Class Variable Within A Instance Method"