了解类以及导致此属性错误的原因

时间:2018-09-04 00:53:39

标签: python python-2.7

我对编码非常陌生,并且学习了如何使用Python。几天前,我开始学习课程,对他们有些困惑,但是我对课程的练习越多,我就越了解。因此,为了练习,我尝试执行此代码,但始终出现属性错误:

>>> class Hero:
     def __init__(self):
         self.health = 100
     def eat (self, food):
         if food == ham:
             print 'Bob has gained health!'
             self.health+=self.HealthBonus
         elif food == poison:
             print 'Oh no! Bob has taken damage!'
             self.health-=self.HealthDown

>>> class Ham:
     def __init__ (self):
         self.name = 'ham'
         self.HealthBonus = 10

>>> class Poison:
     def __init__ (self):
         self.name = 'poison'
         self.HealthDown = 20

>>> bob=Hero()
>>> ham=Ham()
>>> poison=Poison()
>>> bob.eat(ham)
Bob has gained health!
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    bob.eat(ham)
  File "<pyshell#1>", line 7, in eat
    self.health+=self.HealthBonus
AttributeError: Hero instance has no attribute 'HealthBonus'

有人可以帮助我确定此属性错误的原因吗?

1 个答案:

答案 0 :(得分:1)

您的问题就在这里

>>> class Hero:
     def __init__(self):
         self.health = 100
     def eat (self, food):
         if food == ham:
             print 'Bob has gained health!'
             self.health+=self.HealthBonus
         elif food == poison:
             print 'Oh no! Bob has taken damage!'
             self.health-=self.HealthDown

您具有“ self.HealthBonus”,并且self指向拥有当前所调用方法(函数)的类的实例。 Eat由 Hero 类拥有。当您将 food 变量传递给eat方法时,Food是具有健康加成的东西,而不是Hero。更改为此:

>>> class Hero:
     def __init__(self):
         self.health = 100
     def eat (self, food):
         if food == ham:
             print 'Bob has gained health!'
             self.health+=food.HealthBonus
         elif food == poison:
             print 'Oh no! Bob has taken damage!'
             self.health-=food.HealthDown