类没有属性X.

时间:2014-12-31 04:56:03

标签: python oop

我一直在为RPG游戏进行战斗测试。无论出于何种原因,我收到class has no attribute错误。

任何想法如何解决这个问题?

class Enemy:
    def __init__(self, name, H, STR):
        self.name = name
        self.H = H
        self.STR = STR

    def is_alive(self):
        return self.H > 0

    enemyturn = ["1", "2"]

class Goblin(Enemy):
    def __init__(self, name, H, STR):
        name = "Goblin"
        H = 50
        STR = 5

这些类在下面的代码中使用:

if command == "1":
    Goblin.H -= Player.STR
    print("You strike the Goblin for {0} damage.".format(Player.STR))
    random.choice(enemyturn)
    if random.choice == "1":
        Player.H -= Goblin.STR
        print("The Goblin strikes you for {0} damage.".format(Player.STR))
        if random.choice == "2":
            pass
            Combat()

1 个答案:

答案 0 :(得分:3)

在实例化对象之前调用属性。

您应该将它们声明为类变量。

class Enemy:
    name = ""
    H = 0
    STR = 0

    def __init__(self, name, H, STR):
        self.name = name
        self.H = H
        self.STR = STR

    def is_alive(self):
        return self.H > 0


class Goblin(Enemy):
    def __init__(self, name, H, STR):
        self.name = "Goblin"
        self.H = 50
        self.STR = 5