Destructor is a special method and the name should be __del__
Just before destroying an object Garbage Collector always calls the destructor to perform clean-up activities (Resource deallocation activities like close database connection etc).
Once destructor execution is completed the Garbage Collector automatically destroys that object.
Note: The job of the destructor is not to destroy objects and it is just to perform clean-up activities.
Example:
1) import time 2) class Test: 3) def __init__(self): 4) print("Object Initialization...") 5) def __del__(self): 6) print("Fulfilling Last Wish and performing clean up activities...") 7) 8) t1=Test() 9) t1=None 10) time.sleep(5) 11) print("End of application") Output Object Initialization... Fulfilling Last Wish and performing clean up activities... End of application
Example:
1) import time 2) class Test: 3) def __init__(self): 4) print("Constructor Execution...") 5) def __del__(self): 6) print("Destructor Execution...") 7) 8) list=[Test(),Test(),Test()] 9) del list 10) time.sleep(5) 11) print("End of application") Output Constructor Execution... Constructor Execution... Constructor Execution... Destructor Execution... Destructor Execution... Destructor Execution... End of application
How to find the number of references of an object:
sys module contains getrefcount() function for this purpose.
sys.getrefcount(objectreference)
Example:
1) import sys 2) class Test: 3) pass 4) t1=Test() 5) t2=t1 6) t3=t1 7) t4=t1 8) print(sys.getrefcount(t1)) Output 5
"Python Destructor Not Called"
"Python Destructors"
"Python Destructor Close File"
"Python Destructor Called On
Exception"
"Python Destructor Dict"
"Python Destructor Inheritance"
"Python Destructor Order"
"Python Destructor List"
"Python Destructor Override"