Proxycon
Proxycon

Reputation: 113

Is there a way to let an object call a function after ist own destruction? [python3]

I want a callback function on del object


Explanation

I have a Player Class.

And a Player can have objects of Card in his Player.hand = []

Card instances can be destroyed via del <card_instance>

If a Player has no Cards in his hand , the game is over.

To check that only when necessary, I want a Card to call a Player.check_status() fuction, that checks if the game is over after its own destruction.

Is that possible?


Code

class Player:
     self.hand = [...<Cards>...]

    def check_status(self):
         if self.hand == []:
             print("--- GAME OVER ---")

class Card:
     self.player = <Player_instance>

     def __del__(self):
          del self
          self.player.check_status() # <----- I want to do something like this

Upvotes: 0

Views: 700

Answers (2)

TkTech
TkTech

Reputation: 4976

Unless your object is tied to some external state that needs cleanup no matter what (like a file handle/socket), using __del__ usually isn't the right choice. It's a sign you might be doing something wrong. For example if you wrapped your del in a try...except, then do something else assuming the hand has been changed you'd be wrong. Objects can be (temporarily) kept alive by a try..except block. del card is not the same thing as card.__del__(), it does NOT guarantee __del__ will be called.

Likewise, usually you want your parent to manage it's children, not the other way around. Player's control their cards, cards don't control the player.

Just be explicit with your actions:

class Player:
    def __init__(self):
        self.hand = []

    def add_card(self, card):
        self.hand.append(card)

    def remove_card(self, card):
        self.hand.remove(card)
        if not self.hand:
            print('--- GAME OVER ---')

Upvotes: 3

LeeYawn
LeeYawn

Reputation: 21

Why don't you count the number of cards right after every move and if number of cards equates to 0 then raise your Game Over status.

I am thinking:

  1. Define a function counting the number of cards on hand.
  2. Create a conditional statement that checks if card on hand is equal to 0.
  3. Create a game over function that has the ability to restart game.

Upvotes: 0

Related Questions