In Python, the class may contain data members, member functions (methods), and Python statements. Every class in Python has a special method __del__( ) which executes on an object is out of its scope.
A destructor is a special method or member function of a class which automatically gets executes, on an object is going out of its scope.
The destructor can also be called explicitly using del.
In Python, the destructor is created using a special method called __del__( ). In programming languages like C++, Java, etc. the constructor has the same name as the class name, but in Python, every class has the constructor with same name __del__( ).
class Sample: i = 10 def __init__(self): print(f'Object has created!') def __del__(self): print('Object has destroyed!') obj = Sample()
When we run the above example code, it produces the following output.
- In Python, the method __del__( ) is called as destructor and it is used to destroy an object.
The destructor can also be called manually in Python. We use the following statement to call the destructor.