Destructor being called multiple times

Viewed 27

i am trying to check how new , init and del works and was running below mentioned code , what caught my attention is destructor is being called twice and i don't know the exact reason of it, Can anyone help with it?

class Example:

    # creation of new instance
    def __new__(cls):
        print("example created", object.__new__(cls))
        return object.__new__(cls)

    # Initializing
    def __init__(self):
        print("Example Instance.")

    # Calling destructor
    def __del__(self):
        print("Destructor called, Example deleted.")

obj = Example()
del obj
1 Answers

From geeksforgeeks:

The __del__() method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected. Note : A reference to objects is also deleted when the object goes out of reference or when the program ends.

Python automatically manages memory for you using reference counting and garbage collector. That is, references unnecessary are being automatically deleted.

So you need to create it explicitly to avoid this behavior.

class Example:
   instance = ""

    # creation of new instance
    def __new__(cls):
        instance = object.__new__(cls)
        print("example created", instance)
        return instance

    # Initializing
    def __init__(self):
        print("Example Instance.")

    # Calling destructor
    def __del__(self):
        print("Destructor called, Example deleted.")

result:

>>> obj = Example()
example created <__main__.Example object at 0x7fd0b3efa5b0>
Example Instance.
>>> del obj
Destructor called, Example deleted.
>>>
Related