1.

How does destructor work in a Python class?

Answer»

In object oriented programming, DESTRUCTOR is a method of class which will be automatically called when its object is no longer in use. Python PROVIDES a special (magic) method named __del__() to define destructor. Although destructor is not really required in Python class because Python USES the principle of automatic garbage collection, you can still provide __del__() method for EXPLICIT deletion of object memory.

>>> class Myclass: def __init__(self): print ('object initialized') def __del__(self): print ('object destroyed') >>> x=Myclass() object initialized >>> del x object destroyed

In the above example , ‘del’ keyword in Python is invoked to delete a certain object. As __del__() method is exclusively provided, it is being called.

Python uses reference counting method for garbage collection. As per this method, an object is eligible for garbage collection if its reference count becomes zero.

In the following example, first obj becomes object of Myclass so its reference count is 1. But when we assign another object to obj, reference count of Myclass() becomes 0 and hence it is collected, thereby calling __del__() method inside the class.

>>> class Myclass: def __init__(self): print ('object initialized') def __del__(self): print ('object destroyed') >>> obj=Myclass() object initialized >>> obj=10 object destroyed


Discussion

No Comment Found