Destructors are called upon when an object is about to end. In Python, while using it for data science, we do not need destructors as Python has a garbage collector that handles memory management automatically.
In Python _del_() method is known as a destructor method. When all references to the object are over, it is call upon. In Python deleting an object is known as garbage collection.
Syntax of destructor:
Below we will have a look at an example:
Note: Program calls a destructor after the program has end or all the reference objects get deleted. In simple words, when the reference count becomes zero, and, not when the object went out of scope.
We will understand the above mentioned point through an example.
Now we will have a look at another example to make things clear as day.
In the example above when we call the function fun() an instance of class B is there which passes itself to class A. This will then set a reference to class B and results in a circular reference.
Python’s garbage collector generally removes these kinds of cyclic references, but in the example above as we have write a custom destructor, it makes it uncollectable. As the order in which to destruct is not known so, it leaves them. So, we can understand that if our instances are involved in circular references, they live in memory for a long as the application runs.