Python Polymorphism

Polymorphism means “many forms”. It allows the same method or function name to behave differently depending on the object or data it is working with. Polymorphism is one of the core concepts of Object-Oriented Programming (OOP). Polymorphism with Built-in Functions The same function can work with different data types. Example Output: Polymorphism with Class Methods […]

2 mins read Lesson 20 of 57 35% through track

Polymorphism means “many forms”. It allows the same method or function name to behave differently depending on the object or data it is working with.

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP).

Polymorphism with Built-in Functions

The same function can work with different data types.

Example

print(len("Python"))
print(len([1, 2, 3, 4]))
print(len((10, 20, 30)))

Output:

6
4
3

Polymorphism with Class Methods

Different classes can have methods with the same name.

Example

class Dog:
    def sound(self):
        print("Bark")

class Cat:
    def sound(self):
        print("Meow")

dog = Dog()
cat = Cat()

dog.sound()
cat.sound()

Output:

Bark
Meow

Polymorphism Using a Common Function

Example

class Dog:
    def sound(self):
        print("Bark")

class Cat:
    def sound(self):
        print("Meow")

def animal_sound(animal):
    animal.sound()

animal_sound(Dog())
animal_sound(Cat())

Output:

Bark
Meow

Method Overriding

Polymorphism is commonly achieved through method overriding.

Example

class Animal:
    def sound(self):
        print("Animal Sound")

class Dog(Animal):
    def sound(self):
        print("Dog Barks")

dog = Dog()

dog.sound()

Output:

Dog Barks

Polymorphism with Inheritance

Example

class Vehicle:
    def start(self):
        print("Vehicle Started")

class Car(Vehicle):
    def start(self):
        print("Car Started")

class Bike(Vehicle):
    def start(self):
        print("Bike Started")

vehicles = [Car(), Bike()]

for vehicle in vehicles:
    vehicle.start()

Output:

Car Started
Bike Started

Polymorphism with Functions

Example

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

print(add(10, 20))
print(add("Hello ", "Python"))

Output:

30
Hello Python

Real-World Example

Example

class Payment:
    def pay(self):
        pass

class CreditCard(Payment):
    def pay(self):
        print("Paid using Credit Card")

class UPI(Payment):
    def pay(self):
        print("Paid using UPI")

payments = [CreditCard(), UPI()]

for payment in payments:
    payment.pay()

Output:

Paid using Credit Card
Paid using UPI

Summary

  • Polymorphism means one interface with multiple implementations.
  • The same method name can perform different actions.
  • Method overriding is a common way to achieve polymorphism.
  • Polymorphism improves flexibility and code reusability.
  • Different objects can be treated through a common interface.
  • It is one of the fundamental concepts of OOP.