Reputation: 410
I want to know which one is the best way to access the class variable in a class, either by self, or by class name
I have read somewhere that self is only used for accessing the instance variable. But when I tried with the below code, it is one of the same things. Is is it mean that we can use either of them?
class MyClass:
cls_var = 0 # class variable
def increment(self, incre):
self.cls_var += incre
MyClass.cls_var += incre
def print_var(self):
print(self.cls_var) #Choice 1
print(MyClass.cls_var) # Choice 2
obj1 = MyClass()
obj2 = MyClass()
obj1.increment(5)
obj2.increment(10)
obj1.print_var() #prints 5, 15
obj2.print_var() # prints 15, 15
Upvotes: 1
Views: 506
Reputation: 11789
You should access a class variable only by class name, since that variable is shared among all classes. Thus, to avoid confusion, one should only access class variables by the name of the class; otherwise it might lead to surprising errors (See the second snippet).
Upvotes: 1
Reputation: 107
In my opinion you should use "Choice 2", as the class variable "cls_var" is shared by all instances. So if you do
ob1.increment(5)
also "ob2.cls_var" gets incremented, but Zen of Python sais that explicit is better than implicit! So do
MyClass.increment(5)
See: https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables.
Upvotes: 0