Python Polymorphism

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables a single function or method to operate on different types of objects. In Python, polymorphism can be implemented using inheritance and method overriding.


What is Polymorphism?

Polymorphism means “many shapes” and it allows functions and methods to use objects of different types interchangeably. It provides flexibility and reusability in code by allowing the same interface to work with different underlying forms (data types).




Polymorphism with Inheritance

When a class inherits from another class, it can override methods of the parent class. This is a common way to implement polymorphism.

Base Class: Animal

class Animal:
    def speak(self):
        pass

Derived Class: Dog

class Dog(Animal):
    def speak(self):
        return "Woof!"

Derived Class: Cat

class Cat(Animal):
    def speak(self):
        return "Meow!"


Using Polymorphism

In the example above, the animal_sound function can take any object that belongs to a class derived from Animal and call its speak method.

def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!




Polymorphism with Functions and Methods

Polymorphism isn’t limited to class inheritance. It can also be achieved through functions and methods that work with different types of data.

Example: Polymorphic Function

In this example, the add function works with both integers and strings because the + operator is polymorphic and behaves differently based on the type of its operands.

def add(x, y):
    return x + y

print(add(5, 10))  # Output: 15
print(add("Hello, ", "world!"))  # Output: Hello, world!




Python Labs

Scroll to Top