Python Polymorphism

Polymorphism is a key concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables you to write code that is more generic and flexible, as it can work with different types of objects without needing to know their specific types.

Polymorphism with Inheritance

One way to achieve polymorphism in Python is through inheritance. For example, consider a base classAnimal with a method sound(), and two subclasses Dog andCat that override the sound() method:

class Animal:
    def sound(self):
        raise NotImplementedError("Subclass must implement abstract method")

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

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

You can then create instances of Dog and Cat and call the sound()method on them, even though they are of different types but share a common interface through theAnimal superclass:

dog = Dog()
print(dog.sound())  # Output: 'Woof!'

cat = Cat()
print(cat.sound())  # Output: 'Meow!'

Polymorphism with Duck Typing

Python also supports a concept called "duck typing," where the type or class of an object is determined by its behavior (methods and properties) rather than its explicit type. This allows you to write code that can work with any object that supports the required behavior, regardless of its actual type. For example:

def make_sound(animal):
    return animal.sound()

class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

dog = Dog()
print(make_sound(dog))  # Output: 'Woof!'

cat = Cat()
print(make_sound(cat))  # Output: 'Meow!'

Conclusion

Polymorphism is a powerful concept in OOP that allows you to write more flexible and reusable code. By understanding how to use polymorphism in Python, you can create programs that are more adaptable to different types of objects and requirements.



[ Footer Placeholder]