Destructors are called when an object gets destroyed. It’s the polar opposite of the constructor, which gets called on creation.

These methods are only called on creation and destruction of the object. They are not called manually but completely automatic.

Related course: Python Programming Courses & Exercises

python destructor

A destructor can do the opposite of a constructor, but that isn’t necessarily true. It can do something different. A destructor is a function called when an object is deleted or destroyed.

An object is destroyed by calling:

del obj

Before the object is destroyed, you can do some final tasks. Imagine driving a Tesla and in the code the engine object gets destroyed. No, first you’d want to shutdown the engine, make sure the wheels are not spinning etc.

Take into mind that destroying an object with del is optional, you can create objects and never delete them. They are then only deleted when the program closes. However, this can eat up a lot of memory in large programs.

A destructor has this format:

def __del__(self):
...

It is always part of a class, even if not defined. (If not defined, Python assumes an empty destructor).

Example

The class below has a constructor (init) and destructor (del). We create an instance from the class and delete it right after.

An example of using destructor is shown in the code below:

class Vehicle:
def __init__(self):
print('Vehicle created.')

def __del__(self):
print('Destructor called, vehicle deleted.')

car = Vehicle() # this is where the object is created and the constructor is called
del car # this is where the destructor function gets called

If you run the above program, you can see this output in the terminal:

Vehicle created.
Destructor called, vehicle deleted.

The output is displayed, even though we didn’t call any methods. That’s because a constructor and destructor are called automatically.

If you are a Python beginner, then I highly recommend this book.

Download exercises