×

python · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A inherits everything from its .

lets you build a new class on top of an old one. class Dog(Pet): makes Dog a child class of the parent class Pet. Every method Pet has, Dog gets for free, __init__ included.

To change a method, it: write a method with the same name in the child. Python uses the child's version first, and falls back to the parent's for everything else.

Inside a child, super() reaches the parent, so super().__init__(name) runs the parent's set-up before the child adds more.

class Pet:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f"{self.name} makes a noise"
class Dog(Pet):
    def speak(self):
        return f"{self.name} says Woof!"
print(Pet("Goldie").speak())
print(Dog("Rex").speak())

A child class can have children too, and each one inherits all the way down.