How to Call a Constructor in Python

In Python, a constructor is a special type of method used for initializing the attributes of a class. Unlike in other Object-Oriented languages where you have to explicitly call the constructor, in Python, a constructor is automatically called when an object is created for a class.

What is a Constructor?

In Python, constructors are defined with the help of the init() method. This method is automatically called when an object of a class is created. It’s also used to initialize the attributes of a class. This method can also take parameters, which can be provided at the time of the creation of the object.

Creating a constructor

Constructors in Python are pretty easy to define. All you need is to define a method within your class with the name init(). This method is invoked whenever an object of the class is constructed.

Invoking a constructor implicitly

As I already said, in Python you don’t have to call a constructor explicitly. It automatically gets called every time an object is created for a class. Here’s how you do it:

As you can see above, you don’t need to explicitly call the init() method. This is done by Python internally.

Output Attributes of a Constructor

To access the values assigned to the attributes of a class by a constructor, simply create an object for the class and output its name as follows:

Full Code

Output

John
25
Alice
23

Conclusion

In Python, a constructor is a very crucial part of class definitions. They play a significant role in Object-Oriented Programming by initializing the attributes of a class the moment an object is created for it. It’s important to understand that the constructor is not explicitly called. It’s Python’s beauty that it takes care of such invocations internally.