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

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions