What is constructor in Python?

A Constructor is a special member function of a class that creates and returns an object of the class. It is called automatically when an object is created. In programming languages such as Java, C++, etc. constructor has the same name as the class whereas, in Python, the constructor is declared using __init__()code> method.

How to declare constructor in Python?

def __init__(self, param1, param2, param3, ..., paramn):
	statements

Types of constructors in Python

There are two types of constructors in Python-

  1. Default Constructor
  2. Parameterized Constructor

Note:- Python does not support copy constructor. Constructor overloading is not supported in Python which means you cannot define multiple constructors in a class. If you try to declare then you will not get any error but you can only access the last defined constructor. To know more about this visit Constructor Overloading in Python.

Default Constructor in Python

It has no parameters and is called automatically when you create an object without passing any arguments. If you do not define a constructor in a class then Python interpreter generates a default constructor that has an empty body. When you define default or parameterized constructor in a class then Interpreter does not provide a default constructor.

Example of Default Constructor in Python

class Car:
	def __init__(self):
		print('Default constructor is called.')

c = Car()

Output

Default constructor is called.

Parameterized Constructor in Python

It has one or more parameters. These parameters are used used to initialize instance variables. It is called automatically when you create an object and pass arguments during instantiation.

Example of Parameterized Constructor in Python

class Employee:
   def __init__(self, empid, empname):
      self.empid = empid
      self.empname = empname
   def show(self):
      print('Employee ID: ', self.empid)
      print('Employee Name: ', self.empname)
 
e1 = Employee(1, 'Mohit')
e2 = Employee(34, 'Kanchan')
e1.show()
e2.show()

Output

Employee ID: 1
Employee Name: Mohit
Employee ID: 34
Employee Name: Kanchan