Summary: In this tutorial, we will learn what is Polymorphism in Python and how can we implement it in Python with the help of examples.

What is Polymorphism in Python?

Polymorphism in general means the condition of occurring in several different forms.

For example, a man can be a father of his child as well as an employee working in a company. A boy who is a student could also be an athlete.

Similar to this, polymorphism also exists in programming.

For example, we can call len() function with different types of objects such as strings, lists, tuples, etc, in Python.

>>> string = 'pencilprogrammer'
>>> len(string)
16
>>> mylist = ['apple', 'ball', 'cricket']
>>> len(mylist)
3

In case of string, the len() function returns the count of characters, while for a list it returns the count of elements.

Another example of polymorphism in Python is the usage of the + operator.

If used with numbers, it adds thems and if used with strings, it joins them.

>>> print(5 + 4)
9
>>> print("Python " + "is " + "programming " + "language")
'Python is programming language'

In both examples, the function or operator performed different operations depending on the type of object or data.

This ability of an entity (function, operator, class, etc) to perform different actions (i.e. have different forms) under different circumstances is known as polymorphism in the context of programming.

How to implement Polymorphism in Python?

Polymorphism is one of the fundamental features of any object-oriented programming language. As Python is also an OOP language, we can easily implement polymorphism using the concept of method overriding.

Method overriding is a feature of OOP in which the child class provides its own implementation of one of the methods of its parent class.

For instance, in the following inheritance example, the class Employee is inheriting the class Person and also has its own implementation of the speak() method:

class Person():
    def speak(self):
        print('Hello..', end='')
        
class Employee(Person):
    def speak(self, greet=False):
        super().speak()
        if greet:
            print('Good Day!')

As we can see, the child class implementation of the speak() method is calling the parent class’s speak() method (using the super() function) and printing additional messages depending on the greet value.

So, when we call the speak method with greet=False, only the parent class’s speak() method output the message. But as we change the parameter value to greet=True, both the speak() methods output their corresponding value to form a complete message.

>>> emp = Employee()
>>> emp.speak(greet=False)
Hello..
>>> emp.speak(greet=True)
Hello..Good Day!

The speak() method here under different conditions perform different actions, which is an example of method polymorphism in Python.

Leave a Reply