Different Types of Variables

Inside the Python class, 3 types of variables are allowed.

  • Instance Variables (Object Level Variables)
  • Static Variables (Class Level Variables)
  • Local variables (Method Level Variables)

Instance Variables

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 

Where we can declare Instance Variables:

We can declare the instance variable in ways

  • Inside the constructor by using the self variable
  • Inside Instance Method by using self variable
  • Outside of the class by using an object reference variable
Inside Constructor by using a self variable:

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:

declaring-instance-variable-inside-the-constructor1

Inside Instance Method by using a self variable:

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:

declaring-instance-variable-inside-the-method1

Outside of the class by using an object reference variable:

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:

declaring-instance-variable-outside-class1

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:

instance-variables-varied-from-object-to-object

How to Access Instance 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:

accessing-instance-variable-inside-and-outside-of-the-class

How to Delete Instance Variables from the Object

Based on our requirement we can delete the instance variables in two ways:

  • deleting the instance variable inside the class :
    we will use del self.variableName
  • Deleting the instance variable outside the class
    We will use 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:

deleting-the-instance-variable-inside-and-outside-the-class

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:

variable-which-is-deleted-from-one-obecvt-cannot-del-from-another-object

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:

changing-the-variavle-value-in-one-object-wonnt-reflect-in-another-object

Static Variables

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 total 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

Where we can Declare Static variable:

We can declare a static variable in various places such as:

In general, we can declare within the class directly but from outside of any method
class Test:
    a=10                  ##Declaring static variable directly in the class but from outside of the method 
print(Test.__dict__)  
​

The output is:

declaring-static-variable-directly-inside-the-class

Inside constructor by using the class name :

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}
Inside the instance method by using the class name
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}
Inside classmethod by using either class name or cls variable :

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}
Inside the static method by using the class name:

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}

How to access static Variables in Python

WE can access the static variable in the following ways such as:

Inside the Constructor by using either self or classname :

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:

accessing-static-variable-inside-the-constructor-by-using-self-and-classname

Inside the instance method: by using either self or classname:

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:

accessing-static-variable-inside-the-instance-method

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:

accessing-static-variable-inside-class-method

Inside the static method: by using classname :

To access the static variable inside the static method, then we have to use @staticmethod decorator and then we can access 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:

accessing-static-variable-inside-static-method

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:

accessing-the-static-variable-outside-the-class

Modifying the Value of Static Variable

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-value-inside-the-class

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:

modifying-static-variable-inside-the-instance-method

Modifying 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

modifying-the-static-variable-inside-class-method-by-using-cls-variable

The output of modifying the static variable by using the class name

modifying-the-static-variable-inside-class-method-by-using-classname

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:

modifying-the-static-variable-inside-static-method-by-using-classname

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:

modifying-static-variable-outside-the-class-by-using-class-name

We cannot modify the static variable value by using the self variable or object reference.

Case study1: The following example demonstrates the difference between instance variable and static variable

The below example is having 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 hence 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 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:

difference-between-instance-variable-and-static-variable

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 access 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)      </pre&g
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions