Polymorphism
Python · Unit 13: Inheritance
- Full plan
- Python
- 10 exercises
If several classes have a method with the same name, you can call it without asking what class each object is: each one answers in its own way. That's called polymorphism.
One loop works for all of them.
class Animal:
def sound(self):
return "..."
class Dog(Animal):
def sound(self):
return "woof"
class Duck(Animal):
def sound(self):
return "quack"
for a in [Dog(), Duck()]:
print(a.sound())Prints
woof quack
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. Predict the output
Each payment method charges its own fee. What does it print?
2. Predict the output
What does this code print?
3. Multiple choice
In the last exercise,
SquareandTridon't inherit from anything. Why did the loop work?4. Find the bug
A car has 4 wheels and a motorbike has 2. It should print 6. Which line has the bug?
5. Predict the output
What does this code print?
6. Complete the code
Complete it to count only the dogs. It should print 2.
7. Put the lines in order
A dog and a hen. Put the lines in order to add up their legs; it should print 6.
8. Multiple choice
This function picks the sound by asking each animal's class. What's the better way?
9. Predict the output
What does this code print?
10. Write the code
Write the
Sellerclass: it inherits fromEmployee, and itspay()is the salary plus a 500 commission. The lines below should print 14500.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.