Customizing destructors in Python

We want to know when the instances of the Rectangle class are removed from memory, that is, when the objects become inaccessible and get deleted by the garbage-collection mechanism. However, it is very important to notice that the ways in which garbage collection works depends on the implementation of Python. Remember that, Python runs on a wide variety of platforms.

Before Python removes an instance from memory, it calls the __del__ method. Thus, we can use this method to add any code we want to run before the instance is destroyed. We can think of the __del__ method as the equivalent of a destructor in other object-oriented programming languages.

The following lines declare a __del__ method within the body of ...

Get Learning Object-Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.