In Python, constructors and destructors are special methods used to initialize and clean up objects of a class.
Constructor: __init__ Method
The constructor in Python is defined using the __init__ method. It is automatically called when a new object of the class is created.
For example,
# Vehicle.py
class Vehicle:
def __init__(self, type, color):
self.type = type
self.color = color
When creating an instance, we must have to pass the constructor arguments. Otherwise, it will throw an Error; like below:
v = Vehicle()
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
v = Vehicle()
TypeError: Vehicle.__init__() missing 2 required positional arguments: 'type' and 'color'
Right way to create an object for Vehicle class is, by passing its’ arguments; like below.
v = Vehicle("SUV", "Blue")
print(v.type, v.color)
Destructor: __del__ Method
The destructor is defined using the __del__ method. It is called when an object is about to be destroyed (usually when it goes out of scope or the program ends).
Adding below destructor code to our Vehicle class example.
def __del__(self):
print("Destructor called.")
Note: In Python, garbage collection is automatic, so destructors are not always predictable in terms of when they are called.
By using the del statement, we can invoke the destructors explicitly.
del v # Explicitly calling destructor
/Shijit/