Polymorphic methods
To design classes effectively, you need to understand how inheritance and polymorphism work together.
In this exercise, you have three classes - one parent and two children - each of which has a talk()
method. Analyze the following code:
class Parent:
def talk(self):
print("Parent talking!")
class Child(Parent):
def talk(self):
print("Child talking!")
class TalkativeChild(Parent):
def talk(self):
print("TalkativeChild talking!")
Parent.talk(self)
p, c, tc = Parent(), Child(), TalkativeChild()
for obj in (p, c, tc):
obj.talk()
What is the output of the code above?
1. | 2. |
|
|
3. | 4. |
|
|
You should be able to complete the exercise just by reading the code, without running it in the console!
This exercise is part of the course
Object-Oriented Programming in Python
Hands-on interactive exercise
Turn theory into action with one of our interactive exercises
