Constructor is a special method used to create and initialize an object of a class. On the other hand, a destructor is used to destroy the object.
After reading this article, you will learn:
- How to create a constructor to initialize an object in Python
- Different types of constructors
- Constructor overloading and chaining
Table of contents
What is Constructor in Python?
In object-oriented programming, A constructor is a special method used to create and initialize an object of a class. This method is defined in the class.
- The constructor is executed automatically at the time of object creation.
- The primary use of a constructor is to declare and initialize data member/ instance variables of a class. The constructor contains a collection of statements (i.e., instructions) that executes at the time of object creation to initialize the attributes of an object.
For example, when we execute obj = Sample(), Python gets to know that obj is an object of class Sample and calls the constructor of that class to create an object.
Note: In Python, internally, the __new__ is the method that creates the object, and __del__ method is called to destroy the object when the reference count for that object becomes zero.
In Python, Object creation is divided into two parts in Object Creation and Object initialization
- Internally, the
__new__is the method that creates the object - And, using the
__init__()method we can implement constructor to initialize the object.
Syntax of a constructor
def __init__(self):
# body of the constructorCode language: Python (python)
Where,
def: The keyword is used to define function.__init__()Method: It is a reserved method. This method gets called as soon as an object of a class is instantiated.self: The first argumentselfrefers to the current object. It binds the instance to the__init__()method. It’s usually namedselfto follow the naming convention.
Note: The __init__() method arguments are optional. We can define a constructor with any number of arguments.
Example: Create a Constructor in Python
In this example, we’ll create a Class Student with an instance variable student name. we’ll see how to use a constructor to initialize the student name at the time of object creation.
Output
Inside Constructor All variables initialized Hello, my name is Emma
- In the above example, an object
s1is created using the constructor - While creating a Student object
nameis passed as an argument to the__init__()method to initialize the object. - Similarly, various objects of the Student class can be created by passing different names as arguments.