Deleting objects

Christopher A. Craig list-python at ccraig.org
Thu Apr 22 10:51:12 EDT 2004


tkpmep at hotmail.com (Thomas Philips) writes:

> Villain dies and executes its destructor (__del__). The game then
> ends. However, when I execute the program in IDLE, IT FINISHES BY
> EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN.
> 
> How can this be? As one of the two objects was destroyed prior to the
> end of the game, how can it be re-destroyed when the program ends?

What's happening is that you're calling self.__del__() (which prints a
string, but does not actually delete the object) and at the end of the
program the object is deleted, which calls self.__del__().  I think
you have the causality backwards, object destruction causes
self.__del__() to be run, self.__del__ does not cause object
destruction.

You are, in fact, guaranteed that the object still exists immediately
after a call to self.__del__() because self must still exist for it to
have been there to be called.  It's also impossible for an object to
commit suicide like that, when you call method(obj) a new reference is
created to "obj", so destroying that refrence cannot destroy the last
reference (since there must still be one in the calling namespace).

This is why delete in python is

del obj

instead of

del(obj)

-- 
Christopher A. Craig <list-python at ccraig.org>
"May the source be with you."  -- Open Source Software mantra





More information about the Python-list mailing list