python3:为什么类的函数运行两次?

2024-10-01 09:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类包含这个攻击函数:

def attack(self, victim):
    strike = 0
    if victim.strength > self.strength:
        strike = 40
    else:
        strike = 70
    successChance = randint(1,100)
    if successChance > strike:
        self.lives -= 1
        return False
    else:
        victim.lives -= 1
        return True

它应该只在用户每次按下一个按钮时运行一次,但是它运行两次,这意味着每按一次按钮都算两次。我知道错误在类函数中,因为错误发生在类的测试运行期间。在

类中唯一调用函数的代码是只在内部运行的测试函数。但是这个问题仍然存在于我的GUI代码中。在

这是我的类函数:

^{pr2}$

Tags: 函数代码selfreturnifdef错误按钮
1条回答
网友
1楼 · 发布于 2024-10-01 09:29:11

如果你在test()中调用了两次函数:

#your old code:
while player.isAlive() == True and opponent.isAlive() == True:
    print(player)
    print(opponent)
    player.attack(opponent) #called once here
    player.isAlive()
    opponent.isAlive()
    if not player.attack(opponent):#called 2nd time here
        print("You lost")
    else:
        print("You won")
print("Game Over")

我要试试这个:

^{pr2}$

相关问题 更多 >