Deleting objects
Terry Reedy
tjreedy at udel.edu
Thu Apr 22 12:17:36 EDT 2004
"Thomas Philips" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0404220608.56bf3d63 at posting.google.com...
> I'm teaching myself OOP using Michael Dawson's "Python Programming For
> The Absolute Beginner" and 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
>
> class Player(object):
> #Class attributes for class Player
> n=0 #n is the number of players
>
> #Private methods for class Player
> def __init__(self,name):
> self.name = name
You appear to have use a tab here and spaces below. Never mix, and stick
with spaces for posted code.
> self.strength = 100
> Player.n +=1
>
> def __del__(self):
> Player.n -=1
> print "I guess I lost this battle"
>
> #Public methods for class Player
> def blast(self,enemy,energy):
> enemy.hit(energy)
>
> def hit(self,energy):
> self.strength -= energy
> if(self.strength <= 50):
> self.__del__()
>
> I instantiate one instance of each class:
> Hero = Player("Me")
> Villain = Alien("Not Me")
>
> If Hero hits Villain with
> Hero.blast(Villain, 100),
>
> Villain dies and executes its destructor (__del__).
However, the name 'Villain' is still bound to the corresponding object in
globals(). Executing the __del__ method of an object does *NOT* delete the
object. This *only* thing special about that method is that it is called
'behind the scenes' when an objects refcount goes to 0.
> The game then
> ends. However, when I execute the program in IDLE, IT FINISHES BY
> EXECUTING THE DESTRUCTOR FOR BOTH HERO AND VILLAIN.
__del__ methods are not destructors. There are merely called be the
interpreter's internal destructor function.
> How can this be? As one of the two objects was destroyed prior to the
> end of the game,
As explained above, it was not destroyed. You merely called a method that
happened to be named __del__.
Getting rid of *all* references to an object, in order to allow destruction
(but not guarantee it), can be difficult.
> how can it be re-destroyed when the program ends?
Terry J. Reedy
More information about the Python-list
mailing list