← All lessons

super()

Sign in · Sign up

Lesson 10.7

A child class can add its own data. The parent's data is handled by super():

class Hero:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

class Mage(Hero):
    def __init__(self, name, hp, mana):
        ...                    # the parent constructor
        self.mana = mana
  • its own __init__ overrides the parent's: without super() the mage would have neither name nor hp;
  • super().__init__(name, hp) means "do what the parent does", not copying its lines;
  • super() is called with brackets: super().__init__(...).

The check gives name, hp and mana. Create a mage and print <name>: <hp> HP, mana <mana>.

Hint

Its own __init__ overrides the parent's.

For the parent data to appear, call the parent first: super() with brackets, a dot, __init__(...) with brackets. Add your own field after that call.