Add def __del__(self): to your class and Python calls it before the object is destroyed.
In Python you rarely need one. The garbage collector already frees memory, and a clean with block closes files and connections for you.
In Python, destructors and constructors are automatically executed, ensuring seamless object lifecycle management without manual intervention.
Understanding Python Destructors
While destructors often handle tasks opposite to constructors, it’s not a strict rule. The main purpose of a destructor is to execute operations just before an object is purged from the memory.
To explicitly destroy an object in Python, you can use:
del obj |
Consider the scenario of operating a Tesla car in software. Before deleting or destroying the engine object, you’d want the program to ensure the engine is turned off and that other related operations are safely completed.
However, it’s essential to understand that using del to destroy objects is not obligatory. While you can instantiate objects without ever deleting them, they will only be removed when the program terminates. This behavior, if not managed well, can lead to memory overhead in extensive applications.
Here’s the typical format for a Python destructor:
def __del__(self): |
By default, all Python classes come with an implicit empty destructor. Hence, even if it’s not defined, the system acknowledges its presence.
Demonstrating Destructors in Python
In the example below, a class named Vehicle has both a constructor (__init__) and a destructor (__del__). After creating an instance of the class, we immediately delete it to observe the destructor in action:
class Vehicle: |
When you execute the above script, you’ll notice the following output:
Vehicle created. |
Interestingly, the output emerges without explicitly calling any methods, underscoring the automatic nature of constructors and destructors in Python’s OOP paradigm.
How it works
Add def __del__(self): to your class and Python calls it before the object
is destroyed. It runs automatically, you do not call it yourself.
It is a good place for cleanup that Python will not do for you: closing a file that is still open, stopping a thread or sending a goodbye message on a socket.
Three things to watch:
- The order of destruction is not guaranteed, so the object may already be partly gone.
- If your program ends,
__del__may not run at all. - An error inside it prints a warning and is ignored, it does not stop the program.
Use with open(...) as f: instead of a destructor for files. The with
block closes the file at the end, also when something goes wrong in the middle.
Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.
