In part-5 we’ll discuss Polymorphism under Python Programming Language.
Polymorphism means that different types respond to the same function.
Polymorphism is very useful as it makes programming more intuitive and therefore easier.
Polymorphism is a fancy word that just means the same function is defined on objects of different types.
Python provides protocols which is polymorphism under the hood. These implement consistent behaviour for built in objects of different type.
To make use of polymorphism, we’re going to create two distinct classes to use with two distinct objects. Each of these distinct classes need to have an interface that is in common so that they can be used polymorphically, so we will give them methods that are distinct but that have the same name.
We’ll create a Shark
class and a Clownfish
class, each of which will define methods for swim()
, swim_backwards()
, and skeleton()
.
class Shark():
def swim(self):
print("The shark is swimming.")
def swim_backwards(self):
print("The shark cannot swim backwards, but can sink backwards.")
def skeleton(self):
print("The shark's skeleton is made of cartilage.")
class Clownfish():
def swim(self):
print("The clownfish is swimming.")
def swim_backwards(self):
print("The clownfish can swim backwards.")
def skeleton(self):
print("The clownfish's skeleton is made of bone.")
In the code above, both the Shark
and Clownfish
class have three methods with the same name in common. However, each of the functionalities of these methods differ for each class.
Let’s instantiate these classes into two objects:
sammy = Shark()
sammy.skeleton()
casey = Clownfish()
casey.skeleton()
When we run the program with the python polymorphic_fish.py
command, we can see that each object behaves as expected:
The shark's skeleton is made of cartilage.
The clownfish's skeleton is made of bone.