Python 3.3类方法不起作用,为什么?

-1 投票
1 回答
3533 浏览
提问于 2025-04-19 23:09

你好,下面是我问题相关的代码:

    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的布尔值,以确定这两个对象是否会打斗。在其他方面它都能正常工作,我本来可以直接用: if p.health <= 0 or e.health <= 0: 但这样的话,我的checkIsAlive()方法就没什么用处了,因为我还想尽可能重复使用代码。我真的搞不懂为什么会这样,希望能理解这个问题。提前感谢你的帮助。

1 个回答

0

正如上面评论中很快指出的那样,我在检查属性名称时犯了一个拼写错误,应该是checkIsAlive。

撰写回答