A constructor is a special type of method (function)specifically used to initialize the instance members of the class.
Constructor can be parameterized and non-parameterized as well.
When we create object of a class, if the program containing Constructor, then it executes automatically.
If a program having no constructor, Python creates a default constructor automatically that does not do anything.
Constructors also verify that there are enough resources for the object to perform any start-up task.
Creating a Constructor
A constructor is a function that begins with double underscore (_). The name of the constructor is always the __init__().
Every class must have a constructor, even if it simply relies on the default constructor.
There are 2 types of constructors like non-parameterized and parameterized constructor.
def __init__(self): #0-arg constructor
Python Non Parameterized Constructor Example
The constructor taking no parameter is known as non-parameterized constructor. Let's see an example for better understanding:
Python Parameterized Constructor Example
The constructor taking parameter is known as parameterized constructor. Let’s see an example: