Polymorphism in Python

Polymorphism in Python refers to the ability to define methods in a class that can take on many forms. It allows objects of different classes to be treated as objects of a common superclass. A common interface can be implemented across different data types.

Polymorphism with Inheritance:

Python
class Animal:
    def speak(self):
        pass

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

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

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

my_dog = Dog()
my_cat = Cat()

make_animal_speak(my_dog)  # Output: Woof!
make_animal_speak(my_cat)  # Output: Meow!

Polymorphism with Functions and Objects:

Polymorphism can also be used with functions and objects:

Python
class Bird:
    def fly(self):
        return "Flying"

class Airplane:
    def fly(self):
        return "Flying in the sky"

def make_it_fly(obj):
    print(obj.fly())

bird = Bird()
airplane = Airplane()

make_it_fly(bird)       # Output: Flying
make_it_fly(airplane)   # Output: Flying in the sky

Polymorphism enhances flexibility in your code by allowing a unified interface to interact with different data types.