Deleting objects

Robert Brewer fumanchu at amor.org
Thu Apr 22 12:24:45 EDT 2004


Thomas Philips wrote:
> 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
>         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__). 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?

A couple points:

1. Forget what you know about 'private' and 'public' members. For now,
create every attribute and method as if it were public. You can add back
in concepts of 'private' members in a couple weeks, if you still feel
you need them.

2. __del__ is not a destructor; that is, when you call:

        if(self.strength <= 50):
            self.__del__()

self is not destroyed. Read
http://docs.python.org/ref/customization.html for the spec on __del__.
Instead, you might try a container (like a list) which holds Player
instances:

players = []

class Player(object):
    def __init__(self,name):
        self.name = name
        self.strength = 100
     
    def blast(self,enemy,energy):
        enemy.hit(energy)
 
    def hit(self,energy):
        self.strength -= energy
        if(self.strength <= 50):
            print "I guess I lost this battle"
            players.remove(self)


Hero = Player("Me")
players.append(Hero)

Villain = Player("Not Me")
players.append(Villain)

Hero.blast(Villain, 100)

print players


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list