Python Object Oriented Programming Language

Python is a multi-programming language, as it supports different programming approach, in that the most popular approach is to solve a programming problem by creating an object, this is known as an Object-oriented programming language.

The Three Important terms of Oops concept are:

  • Class : A Class is nothing but a plan/blueprint/template/model.
  • Object : A Physical existence/An Instance of a class is called an Object.
  • Reference Variable : A variable that is used to refer to an object are called reference variables, The main purpose of the reference variable is to perform required operations on python objects.

Class

In Python, everything is an object, To create objects we required some Model or Plan or Blueprint which is nothing but a class.

  • We can write a class to represent some properties (attributes) and actions (behavior) of an object.
  • Properties can be represented by variables
  • Actions can be represented by Methods.
  • Hence class contains both variables and methods.

How to define a Class?

We can define a class by using the class keyword.

The Syntax for the class is:

class className:

 ''' documentation string '''

 variables:instance variables,static and local variables

methods: instance methods, static methods, class methods

The documentation string represents the description of the class. Within the class, a doc string is always optional. We can get a doc string by using the following 2 ways.

  • print(classname.__doc__): where __doc__ is a predefined variable that can be used to access the documentation string of the class.
  • help(classname)

Example:

class Student:
    '''This class developed by chercher.tech for demo purpose'''
    #variables
    #methods
print(Student.__doc__)

The output is:

accessing-student-documentation-string-of-class

We can also access the student class by using the help(student)

class Student:
    '''This class developed by chercher.tech for demo purpose'''
help(Student)

The output is:

accessing-student-by-using-help

Within the Python class, we can represent data by using variables

There are three types of variable are allowed :

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

Within the python class, we can represent the operations by using the Methods, The following are the various types of methods available in python :

  • Instance Method
  • Class Method
  • Static Method

The following example demonstrates how to access the class and how to define methods and how to call a method by using class

class Student:
    '''This class developed by chercher.tech for demo purpose'''
    def __init__(self):
        self.name="chercher.tech"     ###Defining a Method
        self.rollno=101
        self.marks=90
        
    def talk(self):
        print("Hello my Name is:",self.name)
        print("My Roll is:",self.rollno)        ##Defining another Method
        print("My Marks are:", self.marks)
        
s=Student() ## Defining a  reference variable
print(s.name)   ## by using reference variable accessing the propertiese of an object
print(s.rollno)   ## by using reference variable accessing the propertiese of an object
print(s.marks)   ## by using reference variable accessing the propertiese of an object
s.talk()     #### by using reference variable calling a method

The output is:

output-of-demo-program-of-class-and-methods

The following example demonstrates how to define the class and how to define methods and how to call methods.

class Student:
    def __init__(self,name,rollno,marks):
        self.name=name
        self.rollno=rollno
        self.marks=marks
        
    def talk(self):
        print("Hello my Name is:",self.name)
        print("My Roll is:",self.rollno) 
        print("My Marks are:", self.marks)
        
s1=Student("Atharva",80,45)
s2=Student("Dhanu",67,93)
s1.talk()
s2.talk()

The output is:

accesing-methods-and-objects

Self Variable

The Self is the default variable which is always pointing to the current object (like this keyword in Java)

By using self we can access instance variables and instance methods of the object.

We should use the self within the python class to refer to the current object.

1) self should be the first parameter inside the constructor: def __init__(self):
2) self should be the first parameter inside instance methods: def talk(self):

The following example demonstrates the use of a self variable in the python program

Let us consider, we have created a class called test and inside this test class we are defining a __init__ () the method by using a self variable.

And also I am creating an object by using T, we can assign a Test object to T outside of the class and hence to access this object inside the class we are using the self variable.

Now, Self and T both are pointing to the same object, let us prove this with the following example:

class Test:
    def __init__(self):
        print("The address of an object pointing by self variable:",id(self))
T=Test()
print("The address of an object poiting by T:",id(T))

The output is:

self-variable-and-obect-poiniting-to-the-same-object

The following example demonstrates the constructor in the class

Consider a class that contains one constructor and one method, The first argument to the constructor and to the instance method is always self.

Now, let us create an object, So whenever we create an object automatically the constructor will be called but we are not passing any value to the self argument from here because the python is responsible for assigning a value to self and instance variables.

But the instance method is having two arguments such as self and x, we only required to assign a value to x.

class Test:
    def __init__(self):            ##constructor
        print("Constructer")
    def m1(self,x):               ##Method
        print("x value is:",x)
T=Test()
T.m1(10)

The output is:

assigning-vaue-to-instance-variabe

Python is not a keyword, instead, you can use any other keyword, but preferred to use self

class Test:
    def __init__(kelf):
        print("Constructor")
    def m1(kelf,x):
        print("x value is:",x)
T=Test()
T.m1(10)

The output is:

kef-instaed-of-self

The first argument whatever we are passing is treated as a self argument and python is responsible for assigning values to it.

class Student:
    def __init__(name, roll no, marks):  ##here the name argument is treated as a self argument and python is going to assign a value to it
        self.name=name
        self.rollno=rollno
        self.marks=marks
        
    def talk(self):
        print("Hello my Name is:",self.name)
        print("My Roll is:",self.rollno) 
        print("My Marks are:", self.marks)
        
s1=Student("Atharva",80,45) ##here we are passing 3 values including name, but python treats the name as a self variable and try to assign a value then we will get  
s2=Student("Dhanu",67,93)                                                                    a type error
s1.talk()
s2.talk()

The output is:

type-error-of-positional-arguments

The important points to be Remember :

  • Within the python, class to refer to the current object some variable must be required, which is nothing but self.
  • The self is a reference variable always pointing to the current object.
  • The first argument to the constructor and instance method is self
  • At the time of calling the constructor or instance method, we are not required to pass any value to a self variable, internally the python virtual machine is responsible to provide value.
  • The main purpose of the self variable within the class is to declare an instance variable and access the values of instance variables.
  • The self is not a keyword, instead, we can use any other key but recommended to use self.
  • We cannot use self outside the class.

Python Constructor

  • The constructor is a special method in python.
  • The name of the constructor should be always __init__(self)
  • The constructor will be executed automatically at the time of object creation.
  • The main purpose of a constructor is to declare and initialize instance variables.
  • The constructor will be executed only once per object.
  • The constructor can take at least one argument(at least self)
  • The constructor is optional and if we are not providing any constructor then python will provide a default constructor.

The following example demonstrates the execution of a constructor

class Test:
    def __init__(self):
        print("Constructor Execution..")
T1=Test()
T2=Test()
T3=Test() 

The output is:

execution-of-constructor-without-calling-explicitly

The following example demonstrates the initialization of instance variable by using constructor

class Student:
    def __init__(self,name,rollno,marks):
        print("creating instance variables and performing initialization")
        self.name=name      ##declaring instance variable
        self.rollno=rollno     ##declaring instance variable
        self.marks=marks    ##declaring instance variable
        
s1=Student("Raj",45,67)
print(s1.name,s1.rollno,s1.marks)   ##The values will be initialized constructor

s2=Student("Praj",45,89)
print(s2.name,s2.rollno,s2.marks)             ##The values will be initialized by constructor

The output is:

assigning-value-to-instance-variable

The following example demonstrates the constructor is optional inside the class

class Test:
    def m1(self):
        print("Method Execution...")
        
T=Test()
T.m1()     ## python provides the default constructor if we did not call any constructor explicitly

The output is:

constructor-is-not-mandotory-inside-class

The following example demonstrates the calling constructor explicitly

class Test:
    def __init__(self): 
        print("constructor Execution...")
        
T=Test()    ##  we created an object and hence constructor will be executed
T.__init__()     ## we are just calling the constructor explicitly and hence constructor will execute like a normal method
T.__init__()     ## we are just calling the constructor explicitly and hence constructor will execute like a normal method
T.__init__()     ## we are just calling the constructor explicitly and hence constructor will execute like a normal method

The output is:

calling-constructor-explicitly

In python, if two methods with the same name but different arguments, then it is called method overloading, but python won't support method/Constructor overloading

The following example demonstrates the constructor overloading in python

class Test:
    def __init__(self):
        print("no argument constructor")
    def __init__(self,x):    
        print("one-argument constructor")
        
T1=Test()
T2=Test(10)  

The output is:

method-overloading-in-python

Within the python class, we can take more than one constructor, but python is going to consider the latest constructor.

class Test:
    def __init__(self):
        print("no argument constructor")
    def __init__(self,x):    
        print("one-argument constructor")
        
T2=Test(10)  ## Python is going to consider the last constructor

The output is:

considering-last-constructor

The following example demonstrates an object-oriented programming language.

class Movie:
    '''Movie class developed by chercher.tech for Python demo purpose'''
    def __init__(self,title,hero,heroine):
        self.title=title
        self.hero=hero
        self.heroine=heroine
        
    def info(self):
        print("Movie Name:", self.title)
        print("Hero Name:", self.hero)
        print("Heroine Name:", self.heroine)
         
list_of_movies=[]
while True:
    title=input("Enter Movie Name:")
    hero=input("Enter Hero Name:")
    heroine=input("Enter Heroine Name:")
    m=Movie(title, hero, heroine)
    list_of_movies.append(m)
    print("Movie added to the list successfully...")
    option=input("Do you want to add one more movie [Yes|No]:")    
    if option.lower()=='No':
        break
    
print("All Movies Information...")
for movie in list_of_movies:
    movie.info()
    print()    

The output is:

Enter Movie Name: Bahubali
Enter Hero Name: Prabhas
Enter Heroine Name: Anushka
The movie added to the list successfully...
Do you want to add one more movie [Yes|No]: yes
Enter Movie Name: KGF
Enter Hero Name: Yash
Enter Heroine Name: Radhika
The movie added to the list successfully...
Do you want to add one more movie [Yes|No]: yes
Enter Movie Name: Krish
Enter Hero Name: Hrithik
Enter Heroine Name: Priyanka
The movie added to the list successfully...
Do you want to add one more movie [Yes|No]: no
All Movies Information
Movie Name: Bahubali
Movie Hero: Prabhas
Movie Heroine: Anushka

Movie Name: KGF
Movie Hero: Yash
Movie Heroine: Radhika

Movie Name: Krish
Movie Hero: Hrithik
Movie Heroine: Priyanka

The Difference Between Method and Constructor

Method Constructor
Name of the method can be any name Constructor name should be always __init__

The method won't execute automatically we have to call explicitly, then the only method will be executed.

The constructor will be executed automatically whenever we are creating an object and we are not required to call explicitly.

Per object, the method can be called any number of times Per object, Constructor will be executed only once
Inside the method, we can write business logics based on our programming requirement Inside Constructor, we have to declare and initialize instance variables

The following example to demonstrate if the method name and class name are the same

class Test:
    def Test(self):
        print("It is possible to use the class name and method name both are same")
        
T=Test()#Constructor will be executed __init__()
T.Test() #Test() method will be executed 

The output is:

class-name-and-method-name-are-same

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)      

The output is:

casestudy-2

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 is having a constructor __init__(self), we are declaring a variable b=20 inside the constructor by using a self variable.

  • We are creating two objects as t1=Test() and t2=Test()
  • Whenever we are creating an object then automatically the constructor will execute and b=20 will be added to both t1 and t2.
  • If we try to access the variables 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 output
  • Similarly for t2.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.
  • The instance variable 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.
  • And if we try to print the variable value once again, then the print("t1:',t1.a,t1.b) here the instance variable is now available and hence python will print the output as 888,999
  • And for print("t2:",t2.a,t2.b) then the instance variable is not available for t2 and hence python will the output as 10,20
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) 
t1.a=888
t1.b=999
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b)

The output is:

case-study-three

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 containing a constructor called __init__(self) with a variable b=20

  • We are creating two objects t1 and t2 then automatically the constructor will execute and adds the value b=20 to both the objects t1 and t2.
  • When we try to access the variables by using the reference object, but currently the instance variable is not available and hence print("t1:",t1.a,t1.b) will print the output as 10,20.
  • Similarly for t2 also print("t2:",t2.a,t2.b) will print the output as 10,20.
  • We are modifying the value of static variable outside the class by using the classname as 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.
  • Now if we try to access the variable by using the object reference then print("t1:",t1.a,t1.b) will print 888,20 because the instance variable a is not there for object t1 and hence it will consider the static variable only.
  • Similarly for t2 also a is not there and hence it will consider the static variable and print("t2:",t2.a,t2.b) will print the output as 888,20.
  • Now, if we try to access the variables outside the class by using the classname then
    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-study-four

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

  • We are creating two objects called 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 objects t1 and t2
  • We are modifying the static variable value outside the class by using the class name as Test.a=888 the value a=888 will be added in both t1 and t2 object
  • And similarly, the value of b also modified by using the reference object as t1.b=999 so the value of b will become 999 in the t1 object only.
  • So the print(t1:",t1.a,t1.b) print the output as 888,999
  • And the value of print(t2:",t2.a,t2.b) will print the output as 888,20
class 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:

case-study-5

Case Study6: The following example is having the class Test with the static variable a=10 and contains a constructor __init__(self) with the variable b=20

  • Now, we are creating two objects called t1=Test() and t2=Test(), whenever we create an object then automatically the constructor will be executed and the value of b=20 will be added to both the objects t1 and t1
  • And also the class is having an instance method method1(self) which is declaring the instance variables by using the self as self.a=888 and self.b=999
  • Now, we are calling the method1() by using the t1 reference object then the instance variables present in the method1 will be added to the object t1 and hence the a=888 and b the value becomes 999 in the t1 object only.
  • If we try to access the variables by using the reference object print("t1:",t1.a,t1.b) will print the output as 888,999
  • Similarly print("t2:",t2.a,t2.b) will print the output as 10,20
class Test:
    a=10
    def __init__(self):
        self.b=20
    def method1(self):
        self.a=888
        self.b=999
                           
      
t1=Test()
t2=Test()
t1.method1()
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b)  

The output is:

case-study-6

Case Study7: The following example is similar to the above example, here I am going to call method1() by using the t1 reference object.

class Test:
    a=10
    def __init__(self):
        self.b=20
    def method1(self):
        self.a=888
        self.b=999
                              
t1=Test()
t2=Test()
t1.method1()
t2.method1()
print("t1:", t1.a,t1.b)
print("t2:", t2.a,t2.b) 

The output is:

case-study7

Case Study8: The Following example containing a Class Test with the static variable declared directly inside the class which contains a constructor __init__(self) with an instance variable b=20.

  • Which again contain classmethod, here the two static variables are declared inside the class method by using the cls variable cls.a=888 and cls.b=999
  • Now we are creating two objects t1 and t2 , whenever we create an object then automatically the constructor will execute and the value b=20 will be added to the objects t1 and t2
  • And now, we are calling a classmethod by using a reference object t1 as t1.method1() , the static variable is already declared at the class level as a=10 but when you call method1() then the static variable value of a will be modified to 888 and a new static variable becomes b=20 in case of a t1 object.
  • If we access the value of variables a and b by using the reference object t1, print("t1:",t1.a,t1.b) print the output as 888 and 20.
  • Similarly, if print the value of variables a and by using the reference object t2, print("t2:",t2.a,t2.b) print the output as 888 and 20
  • And if try to print the value of variables by using the Class name as a print("Test:", Test.a,Test.b) print the output as 888 and 999

Local Variables:

Sometimes to meet temporary requirements of programmer, we can declare variables inside a method directly, such type of variables is called a local variable or temporary variables.

Local variables will be created at the time of method execution and destroyed once the method completes. Local variables of a method cannot be accessed from outside of the method.

Example:
 def info(self):
        x=10 ##Local variable       
        for i in range(n):
        print(i)

Different Types of Methods

Inside the Python class, 3 types of methods are allowed

  • Instance Methods
  • Class Methods
  • Static Methods

Inside method implementation, if we are using instance variables then such type of methods are called instance methods.

Inside the instance method declaration, we have to pass the self variable.

Example: def m1(self):

The First Argument to the instance method is always self, which is a reference variable to that object.

By using the self variable inside method we can able to access instance variables. Within the class we can call the instance method by using self variable and from outside of the class we can call by using object reference.

Class Methods:

Inside method implementation, if we are using only class variables (static variables), then such type of methods we should declare a class method.

We can declare the class method explicitly by using @classmethod decorator. For the class method, we should provide a cls variable at the time of the declaration. We can call the classmethod by using the classname or object reference variable.

The First argument to the class method is always cls is the reference variable to a current class object, by using cls we can access the class-level data.

For every class, one special object will be created by python virtual machine to maintain the class level information, which is nothing but a class level object, cls is the reference variable pointing to that object.

class Test:
    @classmethod
    def m1(cls):
        print(id(cls))
print(id(Test))
Test.m1()

The output is:

class-method

Static Methods:

Inside a method, if we are not using any static variable and instance variable then such type of methods are general utility methods and these methods we declare as static methods.

Static methods should be declared by using @staticmethod decorator.

@staticmethod
def getsum(a,b):
      sum=a+b
      return sum



Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions