Tag: polymorphism
Polymorphism
Sometimes an object comes in many types or forms. If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick(). We access them using the same method . This idea is called Polymorphism.
Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a structure that can take or use many forms of objects.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Polymorphism with a function:
We create two classes: Bear and Dog, both can make a distinct sound. We then make two instances and call their action using the same method.
class Bear(object): |
Output:
Groarrr |
Polymorphism with abstract class (most commonly used)

Abstract structure is defined in Document class.
If you create an editor you may not know in advance what type of documents a user will open (pdf format or word format?).
Wouldn’t it be great to acess them like this, instead of having 20 types for every document?
for document in documents: |
To do so, we create an abstract class called document. This class does not have any implementation but defines the structure (in form of functions) that all forms must have. If we define the function show() then both the PdfDocument and WordDocument must have the show() function. Full code:
class Document: |
Output:
Document1: Show pdf contents! |
We have an abstract access point (document) to many types of objects (pdf,word) that follow the same structure.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Polymorphism example

Another example would be to have an abstract class Car which holds the structure drive() and stop().
We define two objects Sportscar and Truck, both are a form of Car. In pseudo code what we will do is:
class Car: |
Then we can access any type of car and call the functionality without taking further into account if the form is Sportscar or Truck. Full code:
class Car: |
Output:
Bananatruck: Truck driving slowly because heavily loaded. |
If you are new to Python programming, I highly recommend this book.