Deleting objects - my earler post got garbled

"Martin v. Löwis" martin at v.loewis.de
Thu Apr 22 16:51:51 EDT 2004


Thomas Philips wrote:
> I have a question about deleting objects. My game has two classes,
> Player and Alien, essentially identical, instances of which can shoot
> at each other. Player is described below

There are a few problems with your posting. First of all, you don't
show the code of Alien.

>     def hit(self,energy):
>         self.strength -= energy
>         if(self.strength <= 50):
>             self.__del__()

Then, you are invoking __del__ explicitly. This is probably not
what you want to do. Invoking __del__ does *not* cause the object
to be deleted.

I repeat. Invoking __del__ does *not* cause the object to be
deleted.

Instead, it is vice versa: Deleting the object causes __del__
to be invoked. The object is deleted when the last reference
to the object goes away, *not* when __del__ is invoked.

So in your example, you cause multiple calls to __del__.
This is probably not what you want to do.

There is no way to explicitly delete an object in Python.

> 1. 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?

This is hard to tell, because you don't show the code of Alien.

> 2. After Hero hits Villain with an energy of 100, Villain executes its
> destructor, but I find I can then type
> Villain.blast(Hero,100)
> and have the alien (whose demise had me gloating) blast me right back!
> Why is it that the blast() method works for an object whose destructor
> has been executed?

Because invoking __del__ does not cause the object to go away. There
is no way to explicitly delete an object in Python.

Regards,
Martin




More information about the Python-list mailing list