196. Polymorphism in OOP

Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as instances of the same class through a common interface. In Python, polymorphism can be implemented using method overriding, allowing subclasses to provide their own implementations of methods defined in a parent class.

Here are 10 Python code snippets demonstrating the implementation of polymorphism through method overriding and related concepts.


1. Basic Polymorphism Example

class Animal:
    def speak(self):
        return "Some generic sound"

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

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

# Polymorphism in action
def animal_speak(animal: Animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_speak(dog)  # Outputs: Woof
animal_speak(cat)  # Outputs: Meow

2. Polymorphism with Multiple Inheritance


3. Polymorphism with Abstraction (Abstract Base Class)


4. Polymorphism with Method Resolution Order (MRO)


5. Polymorphism with Dynamic Method Overriding


6. Polymorphism in a Real-World Example (Payment System)


7. Polymorphism with Method Overloading (using default arguments)


8. Polymorphism in a Drawing Application (Shape Classes)


9. Polymorphism with Duck Typing


10. Polymorphism in a Sorting Application (Sortable Classes)


Key Concepts:

  • Method Overriding: Subclasses provide their own implementation of methods defined in a parent class.

  • Polymorphism: Objects of different classes can be treated uniformly when they implement the same method signature.

  • Duck Typing: Python's dynamic nature allows polymorphism without requiring a strict class hierarchy.

  • Multiple Inheritance: Polymorphism can extend to multiple parent classes, allowing more flexibility.

  • Abstract Base Classes (ABCs): Polymorphism can be enforced through abstract methods in base classes.

Polymorphism increases flexibility and reduces code complexity by allowing different classes to share a common interface and behave differently based on the actual class type at runtime.

Last updated