Deleting objects

Discussion in 'Python' started by Thomas Philips, Apr 22, 2004.

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

    Thomas Philips
     
    Thomas Philips, Apr 22, 2004
    #1
    1. Advertising

  2. (Thomas Philips) writes:

    [snip]

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


    Err, __del__ isn't a destructor, it's a finalizer. It's called by the
    Python runtime when it has determined that the object is garbage,
    which is usually immediately after the last reference to it is
    dropped.

    Cheers,
    mwh

    --
    Good? Bad? Strap him into the IETF-approved witch-dunking
    apparatus immediately! -- NTK now, 21/07/2000
     
    Michael Hudson, Apr 22, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jimjim
    Replies:
    0
    Views:
    377
    jimjim
    Feb 27, 2004
  2. dasod

    deleting list objects

    dasod, Jul 4, 2003, in forum: C++
    Replies:
    2
    Views:
    368
    dasod
    Jul 4, 2003
  3. Harry Barker
    Replies:
    2
    Views:
    528
    Alf P. Steinbach
    Apr 19, 2006
  4. 7stud
    Replies:
    11
    Views:
    710
    Dennis Lee Bieber
    Mar 20, 2007
  5. crea
    Replies:
    2
    Views:
    422
    Nobody
    Dec 28, 2012
Loading...

Share This Page