python · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A bike is a vehicle. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Vehicle:
def __init__(self, wheels):
self.wheels = wheels
def describe(self):
return f"I have {self.wheels} wheels"
class Bike(Vehicle):
def ring(self):
return "Ring ring!"
bike = Bike(2)
print(bike.describe(), bike.ring())
your turn
Your turn. Put something in the sale.
Make SaleItem a child of Item, then fill in the word that reaches the parent's set-up. Last, choose a discount, like 0.5 for half price.
fix it
The puppy has no name. Can you fix it?
- Read the error: a Puppy has no attribute called name. Which method normally stores the name?
Puppyoverrides__init__, so the parent's set-up that stores the name never runs.- Add super().__init__(name) as the first line inside Puppy's __init__, then run.
nailed it
you built a family of classes. :D
class Dog(Pet):makes a child class that inherits every method.- Override a method by writing one with the same name.
super().__init__(...)runs the parent's set-up first.
new words in your collection
- inheritance
- parent class
- child class
- override
This lesson isn’t saved. A free account remembers every lesson you finish.