2

Given the code:

class Character():
    def __init__(self, name):
        self.name = name
        self.health = 50
        self.damage = 10

class Warrior(Character):
    def __init__(self, name, weapon, armor):
        super(Character).__init__()
        self.weapon = weapon
        self.armor = armor
        self.strength = 10
        self.dexterity = 5
        self.intelligence = 5

Doug = Character("Doug")
Mark = Warrior("Mark", "Axe", None)

Why doesn't the Warrior class inherit the health from the Character class?
What would I need to do differently to be able to print Mark.health?

martineau
  • 119,623
  • 25
  • 170
  • 301
Matt
  • 23
  • 2
  • `super` is pretty tricky for several reasons; see http://stackoverflow.com/q/222877/1256452 – torek Mar 19 '17 at 13:27

1 Answers1

4

You are using super() incorrectly; don't pass in Character on its own. In Python 3, don't pass anything in at all, but do pass name to __init__:

class Warrior(Character):
    def __init__(self, name, weapon, armor):
        super().__init__(name)
        self.weapon = weapon
        self.armor = armor
        self.strength = 10
        self.dexterity = 5
        self.intelligence = 5

Now attributes are set correctly, including health and damage:

>>> Mark = Warrior("Mark", "Axe", None)
>>> vars(Mark)
{'name': 'Mark', 'health': 50, 'damage': 10, 'weapon': 'Axe', 'armor': None, 'strength': 10, 'dexterity': 5, 'intelligence': 5}

Under the covers, super(Character).__init__() ends up calling the super.__init__() method which within a method on a class just happens to work but produces nothing of practical use (None is returned).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thank you, I've been having trouble grasping the concept of super, making small programs like this to practice. Your comment helped clear up some misunderstanding. – Matt Mar 19 '17 at 12:55
  • if the Character class took more parameters than just 'name' would I need to pass them to the __init__ as well? – Matt Mar 19 '17 at 12:57
  • @Matt: yes, because the `Character.__init__` method would require more parameters. – Martijn Pieters Mar 19 '17 at 13:26