If the value of a variable is not varied from object to object, such types of variables we have to declare within the class directly but outside of methods. Such types of variables are called Static variables.
For the entire class, only one copy of the static variable will be created and shared by all objects of that class. We can access static variables either by class name or by object reference. But recommended using the class name.
class Student:
school _name="Twinkle" ##declaring static variable
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
We can declare a static variable in various places such as:
class Test:
a=10 ##Declaring static variable directly in the class but from outside of the method
print(Test.__dict__)
The output is:
Once we declare the static variable inside the constructor by using the class name, we have to create an object, then automatically the python prints the static variable.
class Test:
a=10
def __init__(self):
Test.b=20 ##Inside constructor by using the class name
t=Test() ####You can see that b=20 will be added to the class dictionary in the below output
## The output is:
{'__module__': '__main__', 'a': 10, '__init__': <function Test.__init__ at 0x01749618>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, 'b': 20}
class Test:
a=10
def __init__(self):
Test.b=20
def method(self):
Test.c=30 ##Inside the instance method by using the class name
t=Test()
t.method() ## Calling instance method will prints the static variable
print(Test.__dict__) ##You can see that c=30 will be added to the class dictionary in the below output
The output is:
{'__module__': '__main__', 'a': 10, '__init__': <function Test.__init__ at 0x00729618>, 'method': <function Test.method at 0x0077BA08>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, 'b': 20, 'c': 30}
If we want to take any method as a class method then compulsory, we have to take a @classmethod decorator.
class Test:
a=10
def __init__(self):
Test.b=20
def method(self):
Test.c=30
@classmethod ## to use any method as a class method then we have to use a decorator
def method1(cls):
cls.d=40 ## inside the class method we can declare the variable either by using cls variable or by using the class name
Test.e=50
t=Test()
t.method()
print(Test.__dict__) ## you can see d=40 and e=50 in the below output
The output is:
{'__module__': '__main__', 'a': 10, '__init__': <function Test.__init__ at 0x0183BA08>, 'method': <function Test.method at 0x0183BA50>, 'method1': <classmethod object at 0x004B9DB0>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
To declare a static variable inside the static method, we have to use a @staticmethod decorator
class Test:
a=10
def __init__(self):
Test.b=20
def method(self):
Test.c=30
@classmethod
def method1(cls):
cls.d=40
Test.e=50
@staticmethod ##use the class method as static method we have to use the @staticmethod decorator
def method2():
Test.f=60 ##declaring the static variable inside the static method by using the class name
t=Test()
t.method()
t.method1()
t.method2()
print(Test.__dict__) ## you can see f=60 in the below output
##The output is:
{'__module__': '__main__', 'a': 10, '__init__': <function Test.__init__ at 0x0086BA08>, 'method': <function Test.method at 0x0086BA50>, 'method1': <classmethod object at 0x006C9EB0>, 'method2': <staticmethod object at 0x006CEE10>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, 'b': 20, 'c': 30, 'd': 40, 'e': 50, 'f': 60}
We can access the static variable in the following ways, such as:
We can access the static variable inside the constructor either by using the self variable or by using the class name but recommended to use the class name
class Test:
a=10
def __init__(self):
print(self.a) ## accessing by using self variable
print(Test.a) ## accessing by using classname
t=Test()
The output is:
If the method is an instance method, then we can access the static variable by using the self variable and class name.
class Test:
a=10
def __init__(self):
print(self.a)
print(Test.a)
def method(self): ##accessing the static variable inside the instance method
print(self.a) ## by using self variable
print(Test.a) ## by using classname
t=Test()
t.method() ##calling instance method
The output is:
To access the static variable inside the class method, then we have to use @classmethod decorator and then by using the cls variable or by using classname.
class Test:
a=10
def method(self):
print(self.a)
print(Test.a)
@classmethod ## decorator
def method1(cls): ##class method
print(cls.a) ##accessing by using the cls variable
print(Test.a) ## accessing by using the classname
t=Test()
#t.method()
t.method1() ## calling the class method
The output is:
To access the static variable inside the static method, then we have to use @staticmethod decorator, and then we can access it by using classname.
class Test:
a=10
def method(self):
print(self.a)
print(Test.a)
@classmethod
def method1(cls):
print(cls.a)
print(Test.a)
@staticmethod Decorator
def method2(): ##static method
print(Test.a) ##byusing class name
t=Test()
#t.method()
#t.method1()
t.method2() ##calling static method
The output is:
To access the static variable outside the class by using either object reference or by using the class name.
class Test:
a=10
def method(self):
print(self.a)
print(Test.a)
@classmethod
def method1(cls):
print(cls.a)
print(Test.a)
@staticmethod
def method2():
print(Test.a)
t=Test()
#t.method()
#t.method1()
#t.method2()
print(t.a) ## accessing the static variable outside the class by using obect reference
print(Test.a) ##accessing the static variable outside the class by using class name
The output is:
We can modify the value of the static variable anywhere (either within the class or outside the class) by using the class name.
class Test:
a=10
def __init__(self):
Test.a=20 ##Modifying the static variable value inside class by using the class name
t=Test() ## craeting an object will automatically calls the constructor
print(Test.a)
The output:
Modifying the static variable value inside the instance method by using the class name
class Test:
a=10
def __init__(self):
Test.a=20
def method(self): ## instance method
Test.a=30 ## modifying the variable value by using class name
t=Test()
t.method()
print(Test.a)
The output is:
Changing the class method by using the cls variable and also by using the class name
class Test:
a=10
def __init__(self):
Test.a=20
def method(self):
Test.a=30
@classmethod ##decorator
def method1(cls): ## class method
cls.a=40 ##modifying by using the cls variable
Test.a=50 ##modifying by using the class name
t=Test()
t.method()
t.method1()
print(Test.a)
The output of modifying the static variable by using the cls variable
The output of modifying the static variable by using the class name
Modifying the static variable value inside the static method by using the class name
class Test:
a=10
def __init__(self):
Test.a=20
def method(self):
Test.a=30
@classmethod
def method1(cls):
cls.a=40
Test.a=50
@staticmethod ##Decorator
def method2(): ## static method
Test.a=60 ## modifying the static variable value by using the classname
t=Test()
#t.method()
#t.method1()
t.method2()
print(Test.a)
The output is:
To Modify the static variable value outside the class by using the class name
class Test:
a=10
def __init__(self):
Test.a=20
def method(self):
Test.a=30
@classmethod
def method1(cls):
cls.a=40
Test.a=50
@staticmethod
def method2():
Test.a=60
t=Test()
#t.method()
#t.method1()
#t.method2()
Test.a=70 ## outside the class by using the class name
print(Test.a)
The output is:
Case study1: The following example demonstrates the difference between instance variable and static variable
The below example has a class method1
and any variable which is calling inside the instance method by using a self variable will become an instance variable.
We are declaring the instance variable with the value a=888
And calling the instance method and hence the instance method is not having any old variable and thus its value becomes 888 only.a=10
.
If we try to access the variable outside the class by using the object reference, then python gives the first priority to an instance variable if the instance variable is not present then it will go for a static variable.
class Test:
a=10
def method1(self):
self.a=888
t1=Test()
t1.method1()
print(Test.a)
print(t1.a)
The output is:
So, we cannot modify the value of the static variable by using the self or by using the object reference, if we are trying to modify the value of the static variable by using self variable and hence static variable won't be modified instead a new instance variable will be created for that object.
Case Study2: If we try to access any variable inside the instance method by using classname then it will always be going to obtain the static variable only and If we try to access the variable outside the class by using the object reference then python gives the first priority to an instance variable if the instance variable is not present then it will go for a static variable, in this case, there is no instance variable and hence python prints the static variable value only
class Test:
a=10
def method1(self):
Test.a=888 ## accessing the static variable by using the classname
t1=Test()
t1.method1()
print(Test.a)
print(t1.a)
The output is:
Case Study3: The following example is having a class named as Test, a static variable will be declared directly at class level as b=20
inside the constructor by using a self variable.
t2=Test()
t2
.print("t1:",t1.a,t1.b)
prints 10,20 as outputprint("t1:", t2.a,t2.b)
prints 10,20 as output.t1
.t1
object.print("t1:',t1.a,t1.b)
here the instance variable is now available, and hence python will print the output as 888,999t2
and accordingly, python will use the output as 10,20class Test:
a=10
def __init__(self):
self.b=20
t1=Test()
t2=Test()
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
t1.a=888
t1.b=999
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b)
The output is:
So, if we are trying to change the value of the static variable by using either self or object reference then the value of the static variable won't be changed; just a new instance variable with that name will be added to that particular object.
Case Study4: The following example containing the class Test with the static variable value as b=20
t2
.print("t1:",t1.a,t1.b)
will print the output as 10,20.Test.b=999
a new static variable will be created because the instance variable is not available and hence python goes to a static variable. print("t1:",t1.a,t1.b)
will print 888,20 because the instance variable is not there for object t1 and hence it will consider the static variable only.print("Test:", Test.a,Test.b)
will print the output as 888,999.class Test:
a=10
def __init__(self):
self.b=20
t1=Test()
t2=Test()
print("t1:",t1.a,t1.b)
print("t2:",t2.a,t2.b)
Test.a=888
Test.b=999
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b)
print("Test:", Test.a,Test.b)
The output is:
Case Study5: The following example contains Test class with the static variable b=20
t2
Test.a=888
the value a=888 will be added in both t1 and t2 objectt1.b=999
so the value of b will become 999 in the t1 object only.print(t1:",t1.a,t1.b)
print the output as 888,999print(t2:",t2.a,t2.b)
will print the output as 888,20class Test:
a=10
def __init__(self):
self.b=20
t1=Test()
t2=Test()
Test.a=888
t1.b=999
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b)
The output is:
We can delete a static variable either by using the class name or by using the cls variables.
The following example demonstrates deleting the static variable
class Test:
num=10
t=Test()
print(t.num) #accessing the static variable
del Test.num #deleting the static variable
The output is:
Instance variable | Static variable |
These are object-level variables | These are class level variables |
For every object, a separate copy will be created | A single copy will be created at the class level and shared by all the objects of that class |
By using one object reference if we are trying to perform any changes to the instance variable, then those changes won't be reflected in the remaining objects, because for every object a separate copy will be created. | If we perform any changes to the static variable, then those changes will be reflected in all the objects, because a single copy of the static variable will be maintained at the class level. |
Sometimes to meet the temporary requirements of the programmer, we can declare a method inside a method directly without using the self,classname or cls variable, such type of variables are called local variables.
The local variables can be used to hold temporary results, the local variables of a method cannot be accessed from outside the method.
The following example demonstrates the local variable
class Test:
@staticmethod
def average(list1):
result=sum(list1)/len(list1)
print("The average:", result)
list1=[10,20,30,40]
Test.average(list1)
The output is:
Example 2:
class Test:
@staticmethod
def average(list1):
result=sum(list1)/len(list1)
print("The average:", result)
@staticmethod
def wish(name):
for i in range(10):
print("Good Evening", name)
list1=[10,20,30,40]
Test.average(list1)
Test.wish("Ashu")
The output is: