A constructor is a method in a Python class that gets executed instantly whenever we create an object for a class.
When we create an object, generally, a constructor is used to initialize instance members of the class to the object’s parameters.
Surely, constructors are treated differently in Python than other programming languages but the basic functionality is almost the same.
Now, let us see how to create a constructor in Python.
Creating a Constructor
The constructor is created using the method named __init__() and this is an in-built method in Python.
When we created an object, the only constructor in the class got executed and two variables got declared i.e., say_hello and say_hi. Now, the object gets to access all of the variables in the constructor.
We can add as many arguments in the constructor as we want, so let us create a constructor with some arguments.
We have defined our class here, now let us use some objects to print something out on the screen.
In this case, we passed a few parameters while creating an object and those parameters got initialized to the attributes inside the __init__() method.
The two examples given above has one key difference, the first one did not have any parameters, on the other hand, the second one had some parameters x and y. This makes us categorize constructors into two different categories.
Types of Constructors
We can categorize constructors in Python into two types:
This is used when we do not want to pass any parameters to pass into the __init__() method. In this case, we might only want to pass a single parameter named self which allows our objects to use attributes present in the method.
When we do have some parameters to pass into a constructor, then we can add parameters to it, and it will become a parameterized constructor. This type of constructor makes use of the resources that Python provides.
To make use of attributes inside the constructor, the parameters are added along with the self parameter.
After creating the class, we are going to use objects to use the methods inside it.
As you can see in the example above, we passed multiple arguments in our object and those arguments got initialized to the attributes in the constructor.
You may wonder, what if we do not create an initializer method in the class and we just simple assign attributes. If you do this then the attributes that you created can still be used by other methods in the class and hence they can be accessed by objects.
These attributes assigned in the class without any method, by default, become a constructor. It does not perform any task but it does initialize the attributes.
The key point that you can understand from here is that you will not get an error if you do not want to create or forgot to create an __init__() method.