Python class destructor | Example code

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):

    # Deleting (Calling destructor)
    def __del__(self):
        print('Destructor called, deleted.')

obj = Employee()
del obj


Python class destructor

Do comment if you have any doubts and suggestions on this Python destructor topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.