Dup Ver Goto 📝

PythonDestructors

PT2/lang/python/old-notes does not exist
To
12 lines, 68 words, 547 chars Page 'PythonDestructors' does not exist.

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()