Skip to content Skip to sidebar Skip to footer

Overriding Destructors Without Calling Their Parents

I'm writing a class that inherits from some library. In said class I'm overriding the destructor so that I can call some function that does cleaning in a certain way. If I don't ca

Solution 1:

No, you need to explicitly call the base classes destructor to ensure that python will delete the object entirely.

From documentation:

If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

Also note that since __del__() method is only called when your object reference count reaches zero, there are Some common situations that may prevent the reference count of an object from going to zero include:

circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_info() keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive).

The first situation can only be remedied by explicitly breaking the cycles; the second can be resolved by freeing the reference to the traceback object when it is no longer useful, and the third can be resolved by storing None in sys.last_traceback. Circular references which are garbage are detected and cleaned up when the cyclic garbage collector is enabled (it’s on by default). Refer to the documentation for the gc module for more information about this topic.

Post a Comment for "Overriding Destructors Without Calling Their Parents"