Adam Schmidt
Adam Schmidt

Reputation: 23

Class has no attribute X

I've been working on making a combat test for a RPG game. For whatever reason I am getting a class has no attribute error.

Any ideas how to fix this?

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

These classes are used in the code below:

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()

Upvotes: 1

Views: 435

Answers (1)

Jivan
Jivan

Reputation: 23068

You are calling your attributes before the objects are instantiated.

You should declare them as class variables.

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

Upvotes: 3

Related Questions