1

Suppose I have the following code in Python:

class Test:
    def __del__(self):
        print("del is called")


a = Test()
a = Test()

yields to the following output:

`del is called`

Why is that and what is the concept behind this?

Is "del" called after every reassignment?

David
  • 2,926
  • 1
  • 27
  • 61

1 Answers1

2

__del__ is called because there's no more references to the original a, causing it to be garbage-collected. See the Python docs for details.

You only get the output once, because

It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

L3viathan
  • 26,748
  • 2
  • 58
  • 81