David
David

Reputation: 3026

Python3: Why is __del__ called after reassignment of a new object variable?

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?

Upvotes: 1

Views: 72

Answers (1)

L3viathan
L3viathan

Reputation: 27273

__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.

Upvotes: 2

Related Questions