Constructors in Python
A constructor is a special method used to create and initialize an object if a class.
On the other hand, a destructor is used to destroy the object.
When we execute obj = Sample(), Python gets to know that obj is an class sample and calls the constructor of that class to create an object.
In python, object creation is divided into two parts in Object Created and Object initialization.
- Internally, the __new__ is the method that create the object.
- And, using the __init__() method we can implement constructor to initialize the object.
Must read Points:
- For every object, the constructor will be executed only once. For example, if we create four object, the constructor is called four times.
- In Python, every class has a constructor, but it’s not required to define it explicitly. Defining constructors in class is optional.
- Python will provide a default constructor if no constructor is defined.