Python Constructor With Example

aimtocode

Python Constructor

A constructor is a special kind of method which is used for initializing the instance variables during object creation.

Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts.

Constructor definition is called automatically whenever an object of that class is created.


Types of constructors in Python

There are two types of Constructors.

  • Default Constructor /Non parameterized Constructor
  • Parameterized Constructor

Syntax of constructor

 def  __init__(self):
         #now all about the constructor

Here, __init__ is used for the constructor to a class. The self parameter refers to the instance of the object (like, this in C++).

Example:

 class Student:
     def __init__(self,name,id):
         self.id = id;
         self.name = name;
     def display (self):
         print(self.id)
         print(self.name)
 Std1 = Student("Prayag", 101)
 Std2 = Student("Rahul", 102)
 Std1.display()
 Std2.display()


Output:

 101
 Prayag
 102
 Rahul

Non-Parameterized Constructor Example

A Constructor, which has no parameter or arguments is called Non-Parameterized constructor.

 class Student:    
     # Constructor - non parameterized    
     def __init__(self):    
         print("This is non parametrized constructor")    
     def show(self,name):    
         print("Hello",name)    
 student = Student()    
 student.show("Prayag")


Output:

 This is non parametrized constructor
 Hello Prayag


Parameterized Constructor Example

A Constructor, which has parameter or arguments is called Non-Parameterized constructor.

class Student:    
     # Constructor - parameterized    
     def __init__(self, name):    
         print("This is parametrized constructor")    
         self.name = name    
     def show(self):    
         print("Hello",self.name)    
 student = Student("Prayag")    
 student.show()

Here, name is assigned as a parameter which is being passed through the constructor __init__.

Output:

 This is parametrized constructor
 Hello Prayag
aimtocode