lang/python/ PythonDestructors
Destructors are one of the special methods of a class.
Destructors are called when an object is garbage collected. __del__
is a special name. __del__
called when the instance is about to be destroyed.
This needn't be when an object loses its last reference, or when del
is called on it.
class A:
def __init__(self,fn):
self.fn = fn
self.file = open(fn)
def __del__(self):
print(f"Closing {self.fn}")
self.file.close()