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
124k29 gold badges181 silver badges319 bronze badges
asked Mar 19, 2017 at 11:38
1

1 Answer 1

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

answered Mar 19, 2017 at 11:41
Sign up to request clarification or add additional context in comments.

3 Comments

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.
if the Character class took more parameters than just 'name' would I need to pass them to the init as well?
@Matt: yes, because the Character.__init__ method would require more parameters.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.