Python variable types
Python variables which are written inside of a class are of 2 types:
- Instance variables
- class variables or static variables
Instance variables are the variables whose separate copy is created in every instance (or object). For example, if 'x' is an instance variable and if we create 3 instances, there will be 3 copies of 'x' in these 3 instances. When we modify the copy of 'x' in any instance, it will not modify the other two copies.
Python Instance Variable example
class Sample: def __init__(self): self.x = 10 def modify(self): self.x+=1 s1 = Sample() s2 = Sample() print('x in s1= ', s1.x) print('x in s2= ', s2.x) s1.modify() print('x in s1= ', s1.x) print('x in s2= ', s2.x)
Python class or static variables example
#class vars or static vars example class Sample: x = 10 @classmethod def modify(cls): cls.x+=1 s1 = Sample() s2 = Sample() print('x in s1= ', s1.x) print('x in s2= ', s2.x) s1.modify() print('x in s1= ', s1.x) print('x in s2= ', s2.x)
A method by the name 'modify' is used to modify the value of 'x'. This method is called 'class method' since it is acting on the class variable. To mark this method as class method, we should use built-in decorator statement @classmethod.
@classmethod #this is a decorator def modify(cls): #cls must be the first parameter cls.x+=1 #cls.x refers to class variable x
A class method contains first parameter by default as 'cls' with which we can access the class variables. For example, to refer to the class variable 'x', we can use 'cls.x'. We can also write other parameters in the class method in addition to the 'cls' parameter.
We can access the class variables using the class methods as: cls.variable. If we want to access the class variables from outside the class, we can use: classname.variable, e.g. Sample.x.