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
You need to use the
@classmethod
decorator:You are confusing classes and instances.
MyClass
is a class,a
is an instance of that class. Your error here is thatupdate
is an instance method. To call it from__init__
, use either:or
Alternatively, make
update
a class method: