Lesson 09
Polymorphism — One Method Name, Many Forms
Override a Python method so one name has many forms, then call the original body with super() when the child still needs it.
Polymorphism means one form in many forms. In this module the original method is the one form. Each overridden method is another form.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- The definition used in this course
- Method overriding: same heading, different body
- Why overriding needs inheritance
super()when the child still wants the parent body
The picture
The purpose is to reuse the method name without keeping a second copy of the original behavior when the child needs a different one.
Method overriding means the heading matches the parent method and the body does not. You need inheritance first. The parent method is the original. The child method is the override.
class GuideNotice(Notice):
def show(self):
return "guide notice"show exists twice. A Notice object runs the original. A GuideNotice object runs the override. One call name, two forms.
super() reaches the original from inside the override:
return super().show() + " for guides"A child can also override __init__. If the child defines __init__ and does not call super().__init__(...), the parent constructor does not run. Call it when the parent fields still need to be set.
Constructor overriding is the same idea as method overriding, applied to __init__. The playground shows method overriding, which is the form you will read most often.
Example
class Notice:
def show(self):
return "general notice"
class GuideNotice(Notice):
def show(self):
return super().show() + " for guides"
for m in (Notice(), GuideNotice()):
print(m.show())The loop uses one name, show, on two kinds of objects. The first line is the original form. The second line is the original form plus the child text, because super() ran the parent body first.
Key takeaways
-
Polymorphism here means one method in many forms
-
Overriding keeps the heading and replaces the body
-
Overriding needs a parent class
-
super()calls the original method -
A child
__init__should callsuper().__init__when the parent fields are still required -
Next: Regular Expressions — search patterns with the
remodule -
Previous: Inheritance
Loading playground…
Check your understanding
Polymorphism quiz
Polymorphism in this lesson means:
1 / 10