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: Complete Python Bootcamp: Go from zero to hero in Python 3

python destructor

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


In code:

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

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

car = Vehicle()
del car

Run the program to see this output:

Vehicle created.
Destructor called, vehicle deleted.

The output is displayed, even though we didn’t call any methods.

Download exercises