← All lessons

Inheritance

Sign in · Sign up

Lesson 10.6

A child class takes everything from its parent:

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

    def hit(self, points):
        ...                # lower the HP and print a line

class Mage(Hero):
    pass
  • class Mage(Hero) means "a mage is a hero": the data and methods of Hero are available on Mage too;
  • pass — Mage has no lines of its own yet, but it inherits the constructor and hit;
  • that's why shared behaviour is written once in the parent instead of copied into each child.

The check gives a name, an HP and the hits. Create a mage and hit it with the inherited method hit(points).

Hint

A child class with no fields and methods of its own is written in two lines.

After the : you need pass — an empty body does not exist. The constructor and hit are inherited, so you don't need to write them again.