Constructor in Python

Constructor in Python

A constructor in Python is a special type of method which is used to initialize the instance members of the class. The task of constructors is to initialize and assign values to the data members of the class when an object of the class is created.

In Python the __init__() method is called the constructor and is always called when an object is created. 


  • class className: 

                def __nit__(Self) #constructor.

Constructor in Python

Function of Constructor:

  • The __init__ method is similar to constructors in c++ and Java.
  • Constructors are used to initialize the object’s state.
  • The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. 


class ClassName:
def __init__( self , variables...):

Types of Constructor: 

  • default constructor: The default constructor is a simple constructor which doesn’t have any argument to pass. Its definition has only one argument which is a reference to the instance being constructed.
  • parameterized constructor: constructor which has parameters to pass is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self. 

Code #1 Default Constructor:

#python Program
#default Constructor 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“A” , self.str1) 

ob = A() 


A PrepInsta
Types of Constructor in Python

Code #2 Parameterized Constructor:

#python Program
#Paremeterized Constructor 
class A(object): 
    def __init__(selfname , userid): = name 

ob = A(‘Rishikesh’ , [email protected])

Constructor Overloading :

  • If you give it more than one constructor, that does not lead to constructor overloading in Python.
#python Program


class A(object): 


    def __init__(self,name,age): 

  = name
    def __init__(self,name,age,g): = name
    def display(self):
#Raise Error