Types of variables
There are two types of variable:
Instance variable
Class variable
Instance variable:
This variable is called instance variable because separate copy is created of every instance. They can be identified with use of self keyword. Instance variable are accessed through constructor and instance method.
Example:
class test:
def __init__(self):
self.x=5
def printdata(self):
self.x=self.x+1
print("X value is",self.x)
t1=test()
t1.printdata()
t2=test()
t2.printdata()
Output:
X value is 6
X value is 6
here the separate copyof x is created for t1 and t2 instance. So we get the output 6 and 6.
Class variable:
The variable that is having only single copy throughout the class is called the class variable. It is shared by all the instances of the class. class variable is also called static variable.
To access class variable class method is used.
The class method is having one parameter called cls. To access the class variable
cls.variable
is written. To access the class variable from outside of the class
classname.variable is written.
Example:
class test:
x=5 #class variable
def __init__(self):
self.y=5 # instance variable
@classmethod # built in decorator
def printdata(cls): #class method
cls.x=cls.x+1
print("X value is",cls.x)
def printdata1(self): #instance method
self.y=self.y+1
print("y value is",self.y)
print("First object")
t1=test()
t1.printdata()
t1.printdata1()
print("Second object")
t2=test()
t2.printdata()
t2.printdata1()
Output:
First object
X value is 6
y value is 6
Second object
X value is 7
y value is 6
The variable that is declared in the class is called class variable. In above example x is class variable. In above code cls is used to identify the class variable. The printdata is class method used to access the class variable. Before printdata @classmethod is used. It is called decorator. This is in built decorator used to identify the class method. The class method have cls as first parameter that is used to access the class variables. We can also write other parameters then the class variable.