Will the following not cause issue of freeing memory twice? Why is python3 destroying an object when it has already been destroyed by the programmer?
class Example: # Initializing def __init__(self): print('object created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, object deleted.') obj = Example() obj.__del__()
Output:
object created. Destructor called, object deleted. Destructor called, object deleted.
Advertisement
Answer
By calling __del__()
you’re just calling a method on the instance, without any special meaning.
The __del__()
method, both yours and by default does absolutely nothing. Moreover, it is not a destructor but rather a finalizer:
Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor.
Python’s memory allocation is completely internal. The only weak guarantee in Python is that if a method __del__()
exists, it will be called right before the object is deleted from memory. It may even be called twice or thrice on certain occasions if the object get resurrected, or not at all in case of daemon threads.
For more info, please read the documentation.