Table of contents
1.
Introduction
2.
What is Polymorphism in Python?
3.
Example of Polymorphism in Python
4.
Function Polymorphism in Python
4.1.
Inbuilt Function
4.2.
Python
4.3.
User-defined function
4.4.
Python
5.
Polymorphism with Class Methods
5.1.
Python
6.
Polymorphism with Function and Objects
6.1.
Python
7.
Polymorphism and Inheritance
7.1.
Python
8.
What Is Method Overriding?
9.
Frequently Asked Questions
9.1.
What is polymorphism encapsulation and inheritance in Python?
9.2.
What is polymorphism in Python medium?
9.3.
What is known as polymorphism?
10.
Conclusion
Last Updated: Jun 21, 2024
Easy

Polymorphism in Python

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

As we all know, Python programming language supports the principles of OOPs. Object-oriented Programming(Oop) is a method that is used to design programs by using classes and objects. One of the fundamental concept of OOPs is Polymorphism. It enables objects to take multiple forms. Polymorphism in Python can be achieved in many ways by using functions, methods, or inheritance.

polymorphism in python

In this article, we will explore the concept of polymorphism in Python. We will discuss how polymorphism can help to write efficient code. We’ll look at some examples of polymorphism in Python. So without any further ado, let's deep dive deeper into our concept.

What is Polymorphism in Python?

The word polymorphism comes from two Greek words poly means many, and morphism means forms. The term polymorphism means that the same function with the same name can be used in different forms. Polymorphism in Oops makes our code more flexible and reusable.

Polymorphism in Python

Polymorphism in Python involves a child class inheriting all the methods from the parent class. In the above example, a boy can be a real-life example of polymorphism. A boy can be a student, a son, or a friend. In Python, we have different ways to define polymorphism. Let us move ahead and see how polymorphism works in Python with examples.

Also see, Python Filter Function

Example of Polymorphism in Python

Polymorphism, in the context of the addition operator, allows it to behave differently depending on the data types involved. For example, it can perform arithmetic addition for numbers and concatenate strings for strings.

# Example 1: Addition of Numbers
result1 = 5 + 3  # Output: 8

# Example 2: Concatenation of Strings
result2 = "Hello, " + "World!"  # Output: "Hello, World!"

 

In the first example, the addition operator performs arithmetic addition because both operands are numbers. In the second example, it concatenates the two strings because they are string data types.
 

Function Polymorphism in Python

Polymorphism in Python can be easily achieved using the polymorphic function. We will look at both the inbuilt function and user-defined functions. So let us move on with their implementation:

Inbuilt Function

Let’s look at the example of how inbuilt function can be used to achieve polymorphism:

  • Python

Python

list = [2, 4, 6]
str = "CodingNinjas"

# For list length
print(len(list))
# For string length
print(len(str))
You can also try this code with Online Python Compiler
Run Code

 

Output

3
12


Explanation

In the above example, the len() function is used for list and string length. It can find both the length of string as well as list. It is an example of inbuilt polymorphic function.

User-defined function

Let’s look at the example of how user-defined function can be used to achieve polymorphism:

  • Python

Python

def add(a, b):
return a + b

# For adding the number
print(add(2, 4))

# Add is used to concatenate the string
print(add("coding", "ninjas"))
You can also try this code with Online Python Compiler
Run Code

 

Output:

6
codingninjas


Explanation

In the above example, we are using add function. We are defining an add function that can add the parameter passed into it. It can be used to add the two numbers. Also, it can be used to concatenate the string ‘coding’ + ‘ninjas’ at the same time.

Polymorphism with Class Methods

In OOPs, polymorphism can be achieved using class methods. It could be done using two or more method with the same name. When a method is called on an object the compiler decides and select the appropriate method. The selection is based on the object's type and argument passed.

  • Python

Python

# Program on sound of cat and dog using class methods
class Animal:
def make_sound(self):
pass

class Cat(Animal):
def make_sound(self):
print("Meow! Meow!")

class Dog(Animal):
def make_sound(self):
print("Bark! Bark!")

def animal_sound(animal):
animal.make_sound()

cat = Cat()
dog = Dog()

animal_sound(cat)
animal_sound(dog)
You can also try this code with Online Python Compiler
Run Code


Output

Meow! Meow!
Bark! Bark!


Explanation

In the above example, we had shown polymorphism with class methods using base class 'Animal.' We defined two derived classes 'Cat' and 'Dog'. Both the classes override the ‘make_sound’ function in their implementation. The function 'animal_sound' takes animal object as an argument and calls ‘make_sound’ method. The method called is dependent on the type of animal objects passes to that function.

 

Polymorphism with Function and Objects

We don’t necessarily have to use polymorphism with classes only. You can use it with functions and objects. The functions are first-class object that we are passed as arguments and return as value. This way, it makes programming more flexible and modular.

  • Python

Python

class State:
def __init__(self, name, capital):
self.name = name
self.capital = capital

def get_info(self):
return f"The capital of {self.name} is {self.capital}."

class UttarPradesh(State):
def __init__(self):
super().__init__("Uttar Pradesh", "Lucknow")

class TamilNadu(State):
def __init__(self):
super().__init__("Tamil Nadu", "Chennai")

class Karnataka(State):
def __init__(self):
super().__init__("Karnataka", "Bengaluru")

def get_capital(state):
print(state.get_info())

uttar_pradesh = UttarPradesh()
tamil_nadu = TamilNadu()
karnataka = Karnataka()

get_capital(uttar_pradesh)
get_capital(tamil_nadu)
get_capital(karnataka)
You can also try this code with Online Python Compiler
Run Code


Output

The capital of Uttar Pradesh is Lucknow.
The capital of Tamil Nadu is Chennai.
The capital of Karnataka is Bengaluru.


Explanation

In the above code,  we define a polymorphism with functions and objects using Indian states and their capitals. State base class has a get_info() method and the three subclasses (UttarPradeshTamilNadu, and Karnataka) that inherit from it and provide their own implementation of the __init__() method. A function get_capital() is used to print information about the state, including its capital. Different objects are created and passed to the get_capital() function, showcasing polymorphism.

Polymorphism and Inheritance

Polymorphism with inheritance involves using a base class and multiple derived classes. Here, with the help of base class we define a common interface, which is then implemented in multiple derived classes. It will also allow objects of different derived classes to be used interchangeably for the time it is with the same interface. The process of implementing a method into the child class is known as Method Overriding.

  • Python

Python

class Human:
def walk(self):
pass

class Adult(Human):
def walk(self):
print("Adult can walk...")

class Infants(Human):
def walk(self):
print("Sorry, infants can't walk...")

def make_human_walk(Human):
Human.walk()

adult = Adult()
infants = Infants()

make_human_walk(adult)
make_human_walk(infants)
You can also try this code with Online Python Compiler
Run Code


Output

Adult can walk...
Sorry, infants can't walk...


Explanation

In the above code,  we define a Human base class with a walk() method and two subclasses Adult and Infants that inherit from Human and provide their own implementation of the walk() method. A function make_human_walk() is defined. It takes a Human object as an argument and calls its walk() method. This function can be used with both Adult and Infants objects, demonstrating polymorphism.

Check this out, Four Pillars of OOPS

What Is Method Overriding?

Method overriding is a feature in object-oriented programming where a subclass provides a specific implementation of a method that is already defined in its superclass. The overridden method in the subclass should have the same name, return type, and parameters as the method in the superclass. This allows the subclass to offer a tailored behavior for the method while maintaining the same interface.

Example in Java:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound();  // Output: Dog barks
    }
}
You can also try this code with Online Java Compiler
Run Code

 

In this example, the Dog class overrides the sound method of the Animal class to provide a specific implementation.

Frequently Asked Questions

What is polymorphism encapsulation and inheritance in Python?

Polymorphism allows objects to be treated as instances of their parent class. Encapsulation hides an object's internal state and only exposes necessary parts. Inheritance lets a class inherit attributes and methods from another class.

What is polymorphism in Python medium?

Polymorphism in Python means different classes can be treated as instances of the same class through a common interface, allowing methods to be used interchangeably, even if their internal implementations differ.

What is known as polymorphism?

Polymorphism is the ability of different objects to respond to the same method call in their own way, allowing for flexible and interchangeable code through a unified interface.

Conclusion

Polymorphism in Python allows a function or method to behave differently depending on the object it operates on. It enables flexibility and code reusability by accommodating various data types or objects. This article provides a concise overview of polymorphism in Python, covering examples and implementation methods. For further knowledge enhancement, feel free to explore our additional blogs.

Live masterclass