Dup Goto 📝

PythonDestructors

PT2/aw/lang/python 07-31 13:46:40
To Pop
12 lines, 68 words, 547 chars Monday 2023-07-31 13:46:40

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