Python Constructors – default and parameterized,
A constructor is a special kind of method which is used for initializing the instance variables during object creation. In this guide, we will see what a constructor, types of it is and how to use them in the python programming with examples.
1. What is a Constructor in Python?
Constructor is used for initializing the instance members when we create the object of a class.
Here we have a instance variable num which we are initializing in the constructor. The constructor is being invoked when we create the object of the class (obj in the following example).
Syntax of constructor declaration
As we have seen in the above example that a constructor always has a name init and the name init is prefixed and suffixed with a double underscore(__). We declare a constructor using def keyword, just like methods.
Types of constructors in Python
Python – default constructor example
Note: An object cannot be created if we don’t have a constructor in our program. This is why when we do not declare a constructor in our program, python does it for us. Lets have a look at the example below.
Example: When we do not declare a constructor
In this example, we do not have a constructor but still we are able to create an object for the class. This is because there is a default constructor implicitly injected by python during program compilation, this is an empty default constructor that looks like this:
Example: When we declare a constructor
In this case, python does not create a constructor in our program.
Python – Parameterized constructor example
When we declare a constructor in such a way that it accepts the arguments during object creation then such type of constructors are known as Parameterized constructors. As you can see that with such type of constructors we can pass the values (data) during object creation, which is used by the constructor to initialize the instance members of that object.