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
selfif you want to be able to alter it in a child class.5, 15, 15, 15. can someone explain how we get this result please?