2014-09-05 73 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中的拼写错误。

相关问题