Updating Class variable within a instance method

60,594

Solution 1

You are confusing classes and instances.

class MyClass(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:

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

Solution 2

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
Share:
60,594

Related videos on Youtube

f.rodrigues
Author by

f.rodrigues

Art major and hobbyist programmer. Interested in Game-Development and Image-Manipulation(Moving and Still). SOreadytohelp

Updated on February 26, 2021

Comments

  • f.rodrigues
    f.rodrigues about 3 years
    class MyClass:
        var1 = 1
    
        def update(value):
            MyClass.var1 += value
    
        def __init__(self,value):
            self.value = value
            MyClass.update(value)
    
    a = MyClass(1)
    

    I'm trying to update a class variable(var1) within a method(_init_) but I gives me:

    TypeError: unbound method update() must be called with MyClass instance as first argument (got int instance instead)
    

    I'm doing this because I want easy access to all variables in a class by calling print MyClass.var1

  • f.rodrigues
    f.rodrigues over 10 years
    Oh I see, I thought that Class methods were those without the self in it's arguments. Thanks for the clarification.
  • Joe Giusti
    Joe Giusti almost 4 years
    className.var1 += 1 is what i was looking for. I was trying to do self.var1 += 1
  • nascar895
    nascar895 over 2 years
    You are a life saver! Thanks :)