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?
1 Answer 1
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).
3 Comments
Character.__init__ method would require more parameters.Explore related questions
See similar questions with these tags.
superis pretty tricky for several reasons; see stackoverflow.com/q/222877/1256452