Destructors for classes





Hello folks...!!!
Today let us look at destructors for classes in python.

Destructors

The constructors are used for initializing an object. The destructors are used for destroying them. Python has automatic garbage collection, however it will be a good practice to call a destructor at the end so that all the resources linked with it can be cleaned up. the resources include open files, database files. 

"__del__()" is used for defining a destructor. It is invoked by writing del object_name.

One can give any print statement within destructors to explicitly confirm whether destructor is called.

Let us look at an example :

destructors in python

Here the init() initializes and when del object is called, the object destruction can be explicitly viewed.

Disadvantage of destructors

Destructors doesn't work well when there is circular reference. Circular reference is nothing but, when there are more than one class, objects of both the class refer each other. Ambiguity arises which object to destroy first.


Next Topic👉

Comments