Polymorphism

Polymorphism, one of the core concepts in object-oriented programming (OOP), provides the ability to take on many forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. It’s a feature that allows an object to exhibit different behaviors according to its state or the context in which it’s used.

Python Polymorphism with functions and objects

We can create a function that can take any object, allowing for polymorphism. Let’s look at a simple Python program to show how polymorphism works with functions and objects:

 1class Shark():
 2    def swim(self):
 3        print("The shark is swimming.")
 4    def skeleton(self):
 5        print("The shark's skeleton is made of cartilage.")
 6
 7class Clownfish():
 8    def swim(self):
 9        print("The clownfish is swimming.")
10    def skeleton(self):
11        print("The clownfish's skeleton is made of bone.")
12
13shark = Shark()
14clownfish = Clownfish()
15
16for fish in (shark, clownfish):
17    fish.swim()
18    fish.skeleton()

Polymorphism with inheritance

With inheritance, the child class inherits methods from the parent class. However, there are situations where the method inherited from the parent class doesn’t quite fit into the child class. In such cases, we re-implement the method in the child class. This process is known as Method Overriding. Overriding is, therefore, a part of the polymorphism feature.

 1class Bird:
 2  def intro(self):
 3    print("There are many types of birds.")
 4  def flight(self):
 5    print("Most of the birds can fly but some cannot.")
 6    
 7class Sparrow(Bird):
 8  def flight(self):
 9    print("Sparrows can fly.")
10    
11class Ostrich(Bird):
12  def flight(self):
13    print("Ostriches cannot fly.")
14   
15obj_bird = Bird()
16obj_spr = Sparrow()
17obj_ost = Ostrich()
18
19obj_bird.intro()
20obj_bird.flight()
21
22obj_spr.intro()
23obj_spr.flight()
24
25obj_ost.intro()
26obj_ost.flight()

With Method Overriding in place, we’re able to ensure that each subclass identifies a method in its own way, which is a key principle of polymorphism.

Note

The method of the child class will always be executed if the parent and child class both have a method with the same name.

Polymorphism not only makes for a cleaner, more intuitive design, but it also makes software more maintainable by making it more scalable and robust.