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.
Complete Python Bootcamp: Go from zero to hero in Python 3
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.
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:
Document1: Show pdf contents!
We have an abstract access point (document) to many types of objects (pdf,word) that follow the same structure.
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:
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:
Bananatruck: Truck driving slowly because heavily loaded.