2013-05-31 93 views
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() 
+6

我們不知道;也許有人稱它爲兩次?函數本身不會調用它自己,我們無法從函數中單獨告訴它爲什麼會被調用兩次。 –

+1

作爲一個快速提示,你在'if'語句的main和'else'子句中定義了'strike',所以最初定義它並沒有意義,因爲它永遠不會被使用。 –

+1

在函數中放置一個斷點,然後檢查堆棧(一系列方法調用)以幫助您理解。如果您的環境中不能有斷點,請嘗試打印它。此引用可能會幫助您打印堆棧:http://docs.python.org/2/library/traceback.html – Lynch

回答

4

那麼,如果看起來像你實際上是在測試()調用該函數兩次:

#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") 

我想嘗試這個:

while player.isAlive() and opponent.isAlive(): 
    print(player) 
    print(opponent) 
    player_attack_was_successful = player.attack(opponent) 
    #player.isAlive() #(does this line even do anything?) 
    #opponent.isAlive() 
    if player_attack_was_successful: 
     print("You won") 
    else: 
     print("You lost") 
print("Game Over") 
+0

感謝堆。我沒有意識到它從if語句中調用函數 – user2368334

相關問題