Composition
Python · Unit 13: Inheritance
- Full plan
- Python
- 9 exercises
Inheritance is for "is a": a dog is an animal. When something "has a" something else, like a car has an engine, you don't inherit: you store the object as an attribute. That's called composition.
c.engine.hp reads left to right: the car's engine and, from that engine, its horsepower.
class Engine:
def __init__(self, hp):
self.hp = hp
class Car:
def __init__(self, hp):
self.engine = Engine(hp)
c = Car(90)
print(c.engine.hp)Prints
90
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Multiple choice
Which of these pairs is best solved with inheritance?
2. Predict the output
What does this code print?
3. Complete the code
Complete it to print the name of the book's author.
4. Predict the output
What does this code print?
5. Predict the output
What does this code print?
6. Complete the code
Ana heals Leo by 20. Complete it so it prints: 50 50
7. Find the bug
This program should print 90. Which line has the bug?
8. Put the lines in order
Put the lines in order to build a playlist. The first song you add should be Hey, and it's the one that gets printed.
9. Predict the output
Inheritance and composition together. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.