【问题标题】:Python 3.3 Class method not working, why? [closed]Python 3.3 类方法不起作用,为什么? [关闭]
【发布时间】:2014-09-05 03:54:16
【问题描述】:

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

    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

【问题讨论】:

  • 这是一个错字。你有checkIsALive(e)。注意大写的“L”。
  • @dano 它甚至没有到达那里,因为错误消息的大小写正确。注意:checkAlive(p) != p.checkAlive()
  • 您的示例代码和您的 实际 代码看起来也不一样。您的示例使用:if p.checkIsAlive() == True and e.checkIsALive() == True。但是你的回溯显示if checkIsAlive(p) == True and checkIsALive(e) == True:,这绝对不是你想要的。
  • @aruisdante 错误消息实际上在其中一个调用上也有错误的大小写。 (checkIsALive(e))
  • 大家好,对不起,是的,我去掉了括号中的 p 和 e,我错误地复制了一个旧的回溯。这个错字显然是导致错误 tyvm 的原因,我很生气自己错过了那个。

标签: python class python-3.3 attributeerror class-attributes


【解决方案1】:

正如在上面的 cmets 中迅速指出的那样。我错过了属性名称 checkIsAlive 中的拼写错误。

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2021-08-27
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多