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 the Rectangle class. Remember that Python always receives self as the first argument for any instance method:
def __del__(self):
print('A Rectangle instance is being destroyed.')The following lines create two instances of the Rectangle class...