Python

Destructor

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 Beyond the Basics – Object-Oriented Programming

Example

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

destructor

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:
abstract-base-classes.md

Vehicle created.
Destructor called, vehicle deleted.

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

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP