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
Dog(Animal)inherits__init__untouched.- Overriding
speakreplaces the base behavior. super().speak()extends the parent instead of replacing it.
Keywords and builtins used here
AnimalDogPuppyclassdefreturnselfspeaksuper
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.
Step 2 of 5 in Classes, step 40 of 72 in Language basics.