Variables in python are nothing but a reserved location to store values of different data types such as List, String, Tuple, Set, Dictionary,etc.. to perform some Operations.
Any names can declare variables or even by alphabets such as
Example: Data, info, a, E,etc..
There Three Different Types of Variables Allowed inside the Python
If the value of a variable is varied from object to object, then such type of variables are called Instance variables or Object-level variables.
For every object, a separate copy of instance variables will be created.
Example: Student Name and Roll no
We can declare the instance variable in ways
We can declare the instance variable inside the constructor.
The following example demonstrates the declaration of instance variable inside the constructor
class Test: def __init__(self): self.a=20 ##a,b are two instance variable declared inside the constructor self.b=30 T=Test() print(T.__dict__)
The output is:
We can declare the instance variable inside the instance method, and when we call that method outside the class, then the instance variable will be executed.
The following example demonstrates the declaring instance variable inside the instance method
class Test: def __init__(self): self.a=20 self.b=30 def method(self): self.c=40 ##Declaring the instance variable inside the method T=Test() T.method() ##calling the method outside the class print(T.__dict__)
The output is:
We can also declare the instance variable outside the class by using the reference of an object.
The following example demonstrates declaring the instance variable outside the class by using the reference variable
class Test: def __init__(self): self.a=20 ##a,b will be added to the object self.b=30 def method(self): self.c=40 ## c will be added to the object T=Test() T.method() T.d=50 ##d will be added to the object print(T.__dict__)
The output is:
The number of instance variables varied from object to object
class Test: def __init__(self): self.a=20 ##a,b will be added to the object self.b=30 def method(self): self.c=40 ## c will be added to the object T1=Test() T1.method() T1.d=50 ##d will be added to the object T2=Test() ## here we called only test object print("T1 dict:", T1.__dict__) print("T2 dict:", T2.__dict__)
The output is:
Python Static Variables
We can access instance variables within the class by using self variable and outside of the class by using an object reference
class Test: def __init__(self): self.a=10 self.b=20 def display(self): print(self.a) ##Accessing the instance varoiable a,b inside the class by using self variable print(self.b) T=Test() T.display() print(T.a) ##Accessing instance variables a,b outside the class by using reference object print(T.b)
The output is:
Console on PyDev
Based on our requirement, we can delete the instance variables in two ways:
del self.variableName
del objectreference.variableName
The following example demonstrates the deleting instance variables inside the class and deleting the instance variable outside the class
class Test: def __init__(self): self.a=10 self.b=20 self.c=30 self.d=40 def method(self): del self.c ## To delete the instance variable inside the class T1=Test() T1.method() ## calling the method will delete the instace variable c print("T1:", T1.__dict__) T2=Test() ## craeted another one object del T2.b,T2.d ## we can delete multiple object outside the class by using the reference object print("T2:", T2.__dict__)
The output is:
The instance variables which are deleted from one object, won't be deleted from another object because, for every object, python creates a separate copy of the instance variables.
class Test: def __init__(self): self.a=10 self.b=20 self.c=30 self.d=40 t1=Test() del t1.a del t2.a print(t1.__dict__) print(t2.__dict__)
The output is:
If we change the values of instance variables of one object, then those changes won't be reflected the remaining objects, because for every object we are a separate copy of instance variables are available
class Test: def __init__(self): self.a=10 self.b=20 t1=Test() t1.a=888 t1.b=999 t2=Test() print("t1:", t1.a,t1.b) print("t2:", t2.a,t2.b)
The output is:
Syntax Error in Python Exception Handling
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:
Python Special characters
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 Test
with the static variable declared directly in the class by the name a=10
and the class is having an instance method called 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.
We are accessing the value of the variable outside the class by using the classname; then it will print the static variable value as a=10
.
If we try to access the variable outside the class by using the object reference, then python gives 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 a=10
, it has a constructor __init__(self)
, we are declaring a variable b=20
inside the constructor by using a self variable.
t1=Test()
and t2=Test()
b=20
will be added to both t1
and t2
.a
and b
by using the object reference then the t1 does not contain the instance variable, and the static variable is available and hence a=10
will be added to the t1
and print("t1:",t1.a,t1.b)
prints 10,20 as outputt2.a
and t2.b
instance variables are not available and hence print("t1:", t2.a,t2.b)
prints 10,20 as output.t1.a=888
If we are declaring any variable by using object reference, then it will become an instance variable for t1.a=888
will be added to the object t1
. b=20
is already available and hence we are modifying the value of b
by using the object reference outside the class t1.b=999
will be added to the t1
object.print("t1:',t1.a,t1.b)
here the instance variable is now available, and hence python will print the output as 888,999print("t2:",t2.a,t2.b)
then the instance variable is not available for t2
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 a=10
and class is also providing a constructor called __init__(self)
with a variable b=20
t1
and t2
then automatically the constructor will execute and adds the value b=20
to both the objectives t1
and t2
.print("t1:",t1.a,t1.b)
will print the output as 10,20.Test.a=888
and 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 a=10
and also contain a constructor __init__(self)
with the variable b=20
t1
and t2
so whenever we create an object, the constructor will execute automatically and the value b=20
will be added to both the objectives t1
and 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:
Python Constructor
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:
Python Dictionary
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: