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. 

Example: 

  • 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. 

Synatx: 

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

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
#Rishikesh 
#constructor 
#default Constructor 
 
class A(object): 
    def __init__(self): 
        self.str1 = “PrepInsta”
        print(“A” , self.str1) 
        

ob = A() 


Output: 

A PrepInsta
Types of Constructor in Python

Code #2 Parameterized Constructor:

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

ob = A(‘Rishikesh’ , ‘abc@.com’)
print(ob.userid) 


Output:

abc@.com

Constructor Overloading :

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

 

#Rishikesh 
#constructor
class A(object): 

 

    def __init__(self,name,age): 

 

        self.name = name
        self.age=age  
    def __init__(self,name,age,g): 
        self.name = name
        self.age=age    
        self.g=g 
        
    def display(self):
        print(self.name,self.age)
    
ob2=A(‘a’,85,78)
print(ob2.g, ob2.name)
ob3=A(1,2)
#Raise Error