2014-09-05 71 views
0

你好是我的問題的相關代碼:Python 3.3類方法不起作用,爲什麼?下面

class Player: 
     def __init__(self, name, x, y, isEvil): 
      self.health = 50 
      self.attack = randint(1, 5) 
      self.name = name 
      self.x = x 
      self.y = y 
      self.isEvil = isEvil 

     def checkIsAlive(self): 
      if self.health <= 0: 
      return False 
     else: 
      return True 

    # implicit in heritance. if the child doesn't have a function that the parent has 
    # the functions of the parent can be called as if it were being called on the 
    # parent itself 

    class Enemy(Player): 


     #def __init__(self, name, x, y, isEvil): 
     # self.health = 50 
     # self.name = name 
     # self.x = x 
     # self.y = y 
     pass 

多一點代碼:

e = Enemy('Goblin', 10, 11, True) 

    p = Player('Timmeh', 0, 1, False) 
    isLight() 

    while True: 
     if p.checkIsAlive() == True and e.checkIsALive() == True: 
      fight() 

     else: 
      if p.checkIsAlive() == True: 
       print('%s is victorious!!! %s survived with %s health points.' % (p.name, p.name, p.health)) 
      else: 
       print('%s shrieks in its bloodlust!!! %s has %s health points' % (e.name, e.name, e.health)) 

然而,當我嘗試和運行此我得到以下錯誤:

Traceback (most recent call last): 
    File "<string>", line 420, in run_nodebug 
    File "C:\Python33\practice programs\textstrat\classees.py", line 94, in <module> 
    if p.checkIsAlive() == True and e.checkIsALive() == True: 
    AttributeError: 'Player' object has no attribute 'checkIsAlive' 

但是,當使用交互式控制檯時,我可以這樣做:

if p.checkIsAlive() == True and e.checkIsAlive() == True: 
    ...  print('they are') 
    ...  
    they are 

我想要做的就是調用checkIsAlive的布爾值來確定兩個對象是否對抗。它適用於所有其他方面,我可以使用: 如果p.health < = 0或e.health < = 0: 但是,這將使我的checkIsAlive()方法非常無用,當我也想能夠回收儘可能多的代碼可能。 我真的不明白爲什麼它會這樣做,並且一定會喜歡理解它。預先感謝您的意見。

+1

這是一個錯字。你有'checkIsALive(e)'。注意大寫'L'。 – dano 2014-09-05 03:59:03

+0

@dano它甚至沒有到達那裏,因爲錯誤信息有正確的大寫。注意:'checkAlive(p)!= p.checkAlive()' – aruisdante 2014-09-05 04:00:32

+0

它看起來像你的示例代碼和你的*實際*代碼是不一樣的。你的例子使用:'如果p.checkIsAlive()== True和e.checkIsALive()== True'。但是你的回溯顯示'如果checkIsAlive(p)== True和checkIsALive(e)== True:',這絕對不是你想要的。 – dano 2014-09-05 04:00:43

回答

0

正如上面評論中所指出的那樣。我錯過了屬性名稱checkIsAlive中的拼寫錯誤。

相關問題