Hi All,
I am new to Python and I came across the Python __del__ method the other day
and I have some doubts on the output of the following code.
So, the snippet code goes something like this:
class Robot():
def __init__(self, name):
print(name + " has been created!")
def __del__(self):
print ("Robot has been destroyed")
if __name__ == "__main__":
x = Robot("Tik-Tok")
y = Robot("Jenkins")
z = x
z
x
del x
del z
del y
Case 1: If I were to run the code in "Script Mode", the following output will
be obtained:
Tik-Tok has been created!
Jenkins has been created!
Robot has been destroyed
Robot has been destroyed
Case 2: If I were to run the code in "Interactive Mode", the following output
will be obtained:
>>> x = Robot("Tik-Tok")
Tik-Tok has been created!
>>> y = Robot("Jenkins")
Jenkins has been created!
>>> z = x
>>> z
<__main__.Robot object at 0x02D7E910>
>>> x
<__main__.Robot object at 0x02D7E910>
>>> del x
>>> del z
>>> del y
Robot has been destroyed
My question being why is that "Robot has been destroyed" is only printed once
in Case 2 (interactive mode) while it is printed out twice in Case 1 (script
mode)?
I did some study on garbage collection and based on my understanding, after the
del x and del z statements, the refcount to the Robot object should reach zero
and subsequently triggers the __del__ method right?
I am hoping someone could provide me a clearer picture on the doubts I have in
mind.
Thanks and Regards,
JY
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor