【问题标题】:Is there a way to let an object call a function after ist own destruction? [python3]有没有办法让对象在自己销毁后调用函数? [python3]
【发布时间】:2019-03-11 03:58:38
【问题描述】:

我想要del object上的回调函数


说明

我有一个Player 类。

Player 可以在他的Player.hand = [] 中包含Card 的对象

Card 实例可以通过del <card_instance> 销毁

如果Player 在他的hand 中没有Cards,则游戏结束。

为了仅在必要时检查,我希望 Card 调用 Player.check_status() 函数,该函数检查游戏是否在自毁后结束。

这可能吗?


代码

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

【问题讨论】:

    标签: python python-3.x object callback del


    【解决方案1】:

    除非您的对象与某种需要清理的外部状态相关联(例如文件句柄/套接字),否则使用__del__ 通常不是正确的选择。这表明你可能做错了什么。例如,如果您将del 包裹在try...except 中,那么假设手已经改变,您就错了。对象可以(暂时)通过try..except 块保持活动状态。 del card card.__del__() 相同,它不能保证__del__ 会被调用。

    同样,通常您希望您的父母管理它的孩子,而不是相反。玩家控制他们的牌,牌不控制玩家。

    你的行为要明确:

    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 ---')
    

    【讨论】:

      【解决方案2】:

      你为什么不在每次移动后立即数卡片数量,如果卡片数量等于 0,那么提升你的 Game Over 状态。

      我在想:

      1. 定义一个计算手牌数量的函数。
      2. 创建一个条件语句,检查手牌是否等于 0。
      3. 创建一个能够重启游戏的游戏结束函数。

      【讨论】:

        猜你喜欢
        • 2017-06-03
        • 2016-03-07
        • 2014-08-28
        • 2015-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多