Reputation: 135
I want to have a class variable, so that the value can be access in all instances, but I also want to access the variable in methods inside the class. Is that possible? I have tried this, but it didn't work at all.
class myClass:
myvariable = 1
def add():
myvariable+= 1
def print1():
print myvariable
I want to make two instances, one only do add method, the other only do print1 method
Upvotes: 6
Views: 10061
Reputation: 1121534
Yes, just access the variable on the class object:
class myClass(object):
myvariable = 1
def add(self):
myClass.myvariable += 1
def print1(self):
print myClass.myvariable
or if you want to set it per sub-class, use type(self)
:
class myClass(object):
myvariable = 1
def add(self):
type(self).myvariable += 1
def print1(self):
print type(self).myvariable
The difference is that the latter will create a separate attribute on any subclass when set, masking the base class attribute. This is just like setting an attribute on an instance would mask the class attribute.
Although you can get the class attribute via self
as well (print self.myvariable
), explicit is better than implicit here, and avoids accidentally being masked by an instance attribute of the same name. Setting class attributes always has to be done on the class; setting it on self
would create or update an instance attribute instead (not shared).
Do inherit your classes from object
though; using new-style classes has many advantages, not in the least that type(self)
will then actually return the class. In old-style classes (not inheriting from object
) you'd have to use self.__class__
instead.
Using object
as a base also gives you a third option, class methods with the @classmethod
decorator; use these when you only need to access the class object, not the instance. These methods are bound to the current (sub)class, so their effect on class attributes is the same as using type(self)
:
class myClass(object):
myvariable = 1
@classmethod
def add(cls):
cls.myvariable += 1
@classmethod
def print1(cls):
print cls.myvariable
Upvotes: 14