0
我有一个包含这种攻击功能类:Python 3:为什么我的类的函数运行两次?
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代码中。
这是我的类函数:
class Player(object):
def __init__(self, name="", lives=DEFAULT_LIVES):
self._name = name
self.lives = lives
self.strength = randint(1,10)
if self._name== "Test":
self.lives = 1000
if self._name== "":
self._name = "John Smith"
def __str__(self):
return (self._name + " Life: " + str(self.lives) + " Strength: " + str(self.strength))
def getLives(self):
return self.lives
def getStrength(self):
self.strength = randint(1,10)
return self.strength
def getName(self):
return self._name
def isAlive(self):
if self.lives <= 0:
return False
return True
def attack(self, victim):
if victim.strength > self.strength:
strike = 40
else:
strike = 70
successChance = randint(1,100)
if successChance > strike:
print(successChance)
self.lives -= 1
return False
else:
print(successChance)
victim.lives -= 1
return True
def test():
player = Player("Tyler")
opponent = Player(choice(opponentList))
while player.isAlive() == True and opponent.isAlive() == True:
print(player)
print(opponent)
player.attack(opponent)
player.isAlive()
opponent.isAlive()
if not player.attack(opponent):
print("You lost")
else:
print("You won")
print("Game Over")
if __name__ == '__main__':
test()
我们不知道;也许有人称它为两次?函数本身不会调用它自己,我们无法从函数中单独告诉它为什么会被调用两次。 –
作为一个快速提示,你在'if'语句的main和'else'子句中定义了'strike',所以最初定义它并没有意义,因为它永远不会被使用。 –
在函数中放置一个断点,然后检查堆栈(一系列方法调用)以帮助您理解。如果您的环境中不能有断点,请尝试打印它。此引用可能会帮助您打印堆栈:http://docs.python.org/2/library/traceback.html – Lynch