Skip to content

Python class destructor | Example code

  • by

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 demonstration

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

Output:

Python class destructor

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading