typestar

Inheritance and super in Python

Subclasses: sharing a base and overriding what differs.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"


class Dog(Animal):
    def speak(self):
        return f"{self.name} says woof"


class Puppy(Dog):
    def speak(self):
        return super().speak() + " (squeakily)"

How it works

  1. Dog(Animal) inherits __init__ untouched.
  2. Overriding speak replaces the base behavior.
  3. super().speak() extends the parent instead of replacing it.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
257
Tokens
78
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 2 of 5 in Classes, step 40 of 72 in Language basics.

← Previous Next →