python - 了解类以及导致此属性错误的原因
问题描述
我对编码非常陌生,并且已经开始学习如何使用 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'
有人可以帮我确定此属性错误的原因吗?
解决方案
你的问题出在这里:
>>> 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类所有。当您将食物变量传递给 eat 方法时,食物是具有健康奖励的东西,而不是英雄。改成这样:
>>> 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