下面是我的问题的相关代码:
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&lt; = 0或e.health&lt; = 0: 但是当我还希望能够尽可能多地回收代码时,这会使我的checkIsAlive()方法变得毫无用处。 我真的无法弄清楚它为什么会这样表现并且肯定会喜欢理解它。提前感谢您的意见。
答案 0 :(得分:0)
正如上面的评论中所指出的那样。我错过了属性名称checkIsAlive中的拼写错误。