Types of Polymorphism in Python
Polymorphism means “many forms,” and in programming, it allows the same interface or method to behave differently based on the object or context. Python supports polymorphism, making it flexible and powerful. There are two primary types of polymorphism:
- Compile-time Polymorphism
- Runtime Polymorphism
Let's understand both types and how they apply in Python.
Compile-time Polymorphism
Compile-time polymorphism happens when a method or operation is resolved during the compilation phase. This is common in statically typed languages like Java or C++.
Examples include:
- Method Overloading – having multiple methods with the same name but different parameters.
- Operator Overloading – using the same operator to perform different tasks based on the operand types.
Python does not support true compile-time polymorphism because it is dynamically typed and does not perform method checks at compile time.
However, Python achieves similar behavior using:
- Dynamic Typing – variables can hold values of any type at runtime.
- Duck Typing – if an object behaves like a certain type, it can be used as that type, regardless of its actual class.
This gives Python flexibility similar to compile-time polymorphism, even though it’s resolved at runtime.
Runtime Polymorphism
Runtime polymorphism happens when the method that gets called is decided during program execution, not before.
In Python, method overriding allows child classes to define their own version of a method that exists in the parent class.
Let’s look at an example:
class Animal:
def sound(self):
print("Some generic animal sound")
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
# Polymorphic behavior
for animal in [Dog(), Cat()]:
animal.sound()

You can also try this code with Online Python Compiler
Run Code
Output:
Bark
Meow
In this example, the same method sound() behaves differently based on the object type (Dog or Cat). This decision is made during runtime.
Python’s dynamic nature makes it easy to implement runtime polymorphism, making the code more modular and easier to maintain
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
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
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.
Here is the SEO-optimized, easy-to-read explanation of Polymorphism in OOP (Object-Oriented Programming) with bullet points, simple sentences, and within the required word count:
Polymorphism in OOP (Object-Oriented Programming)
Polymorphism is a key concept in object-oriented programming (OOP). It allows methods with the same name to behave differently depending on the object that calls them. This helps in writing cleaner and more flexible code.
Polymorphism in OOP means that one method name can work in multiple ways based on the object’s class.
It allows different classes to define their own version of a method while sharing the same interface or parent class.
This is made possible using:
- Inheritance – where a child class inherits methods and properties from a parent class.
- Interfaces or Abstract Classes – which define a common structure that different classes can implement in their own way.
Example
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Polymorphic behavior
shapes = [Rectangle(5, 3), Circle(4)]
for shape in shapes:
print(shape.area())

You can also try this code with Online Python Compiler
Run Code
Explanation:
In the above example:
- Both Rectangle and Circle are subclasses of Shape.
- They implement the area() method in their own way.
- When the loop runs, the correct area() method is called depending on the object type.
This is how polymorphism works — the same method name (area) behaves differently based on the object (Rectangle or Circle).
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
# 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
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 (UttarPradesh, TamilNadu, 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
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.