Issues creating a subclass that pulls variables from super() class

Viewed 27

I'm a little bit new to python and I'm currently practicing classes, subclasses and the super() method. I've been creating a small RPG (or at least the base concept) in Python and I've created the base class and can't seem to pull the data in a subsclass.

Here's the relevant code:

class base_human:
    def __init__(self, health, magic, speed):
        self.health = health
        self.magic = magic
        self.speed = speed

## Is the base class

class Warrior(base_human):
    def __init__(self, name):
        self.name = name
        super().__init__(self, health, magic, speed)

## Is my sub class

base_human = base_human(10, 10, 10)

Brian = Warrior("Brian")

print(Brian.health)
print(Brian.name)

## Is the final print to test.

I'm currently getting the following error:

Traceback (most recent call last):
  File "/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py", line 48, in <module>
    Brian = Warrior("Brian")
  File "/Users/zuikis/Desktop/PI Projects/Classes/RPG 2.py", line 32, in __init__
    super().__init__(self, health, magic, speed)
NameError: name 'health' is not defined

Grateful for any help and forgive me if I've made a mistake in the format of the post, any further advice would be well received. Thanks so much.

3 Answers

The Warrior.__init__() method needs to take all the parameters that base_human.__init__() takes, so that it can pass them along when it calls super().__init__().

class Warrior:

    def __init__(self, name, health, magic, speed):
        super().__init__(health, magic, speed)
        self.name = name

Then you need to provide all those values when you create a Warrior:

Brian = Warrior("Brian", 10, 20, 5)

On the other hand, if Warriors all start with the same attributes, you could hard-code them in the super() call.

class Warrior:

    def __init__(self, name):
        super().__init__(10, 20, 5)
        self.name = name

Currently, where does your human class get its health, magic and speed from?

Exactly, it doesn't get them and that's why it is complaining. Your warrior class should have

def __init__(self, name, health, magic, speed):

Look at the class definition

class Warrior(base_human):
    def __init__(self, name):
        self.name = name
        super().__init__(self, health, magic, speed)

Where are you passing health or magic or speed from? No where. None of them are defined. You need to write

class Warrior(base_human):
    def __init__(self, name, health, magic, speed):
        super().__init__(health, magic, speed)
        self.name = name
Related