Python class destructors are called when an object gets destroyed. It’s the opposite of the constructor, which gets called on object creation.
It’s not called manually but completely automatic.
def __del__(self): ...
Python class destructor demostration
Simple example code A destructor is a function called when an object is deleted or destroyed. By using the del keyword we deleted all references of object ‘obj’, therefore the destructor was invoked automatically.
# Python program to illustrate destructor class Employee: # Initializing def __init__(self): print('Created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, deleted.') obj = Employee() del obj
Do comment if you have any doubts and suggestions on this Python destructor topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.