Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
The loop below works for any animal. Add a class Bird that says Tweet, and a class Parrot built on Bird that says the word that it learned, which is given when it is made. Add one of each to the list, and do not change the loop.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. A Bird overrides speak. A Parrot is a kind of bird, so it inherits from Bird, needs one more piece of data (the word), calls super().__init__, and overrides speak again.
Check. The output is Thing makes a sound, Tweety says Tweet, Polly says Hello. The loop was not changed.
Answer: The classes above. New kinds of animal work in the old loop, which is the gain of polymorphism.
Log in to join the discussion.
Loading…