In this chapter, we will discuss Python Variables Types. There are two kinds of variables in any Python class, as listed below.
- Instance Variables
- Static Variables or Class Variables
Python Variables Types – Instance Variables
The variables using which a separate copy gets created for every instance are called Instance Variables.
class InstanceVariables:
#constructor method
def __init__(self):
self.a = 1
#instance method
def updatevalue(self):
self.a+=1
i1 = InstanceVariables()
i2 = InstanceVariables()
print("BEFORE UPDATE")
print('a in i1= ',i1.a)
print('a in i2= ',i2.a)
i1.updatevalue() #update the a value in i1
print("AFTER UPDATE")
print('a in i1= ',i1.a)
print('a in i2= ',i2.a)
Output
BEFORE UPDATE
a in i1= 1
a in i2= 1
AFTER UPDATE
a in i1= 2
a in i2= 1
In the program mentioned above, ‘a’ is an instance variable, and we define them usually within the constructor method with the ‘self’ parameters. They are then accessed by the instance methods that have self as a parameter. The instance methods could also have other parameters along with self.
You can notice that we created two separate instances, i1 and i2. When we updated the value of ‘a’ in the i1 instance, it did not update the value of ‘a’ in the i2 instance. That’s how the instance variables work.
Python Variables Types – Class Variables or Static Variables
We noticed that instance variables vary for each instance. But class variables are available as a single copy to all the class instances.
class ClassVariable:
s = 20 #class variable
#class method
@classmethod
def updatevalue(cls):
cls.s+=1
#let us create two instances now
ins1 = ClassVariable()
ins2 = ClassVariable()
print("BEFORE UPDATE")
print('s in ins1: ',ins1.s)
print('s in ins2: ',ins2.s)
#update s in ins1
ins1.updatevalue()
print("AFTER UPDATE")
print('s in ins1: ',ins1.s)
print('s in ins2: ',ins2.s)
Output
BEFORE UPDATE
s in ins1: 20
s in ins2: 20
AFTER UPDATE
s in ins1: 21
s in ins2: 21
In the program mentioned above, ‘s’ is a class variable. They are usually declared outside the method as mentioned in the program above. They are also called static variables. When you update a static or class variable for any instance, it also updates the class or static variable for all the instances, as shown in the output above.