What is polymorphism?


What is polymorphism?
What is Polymorphism in Python?

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP), allowing objects of different classes to be treated as objects of a common superclass. The term "polymorphism" is derived from the Greek words "poly" (many) and "morph" (form), meaning "many forms."

In Python, polymorphism allows the same function or method to behave differently based
on the object it is acting upon. This increases flexibility and reusability in your code.


Key Concepts of Polymorphism in Python

  1. Method Overloading: Python does not support traditional method overloading (like Java or C++), but it achieves similar behavior by using default arguments or variable-length arguments in functions.

  2. Method Overriding: Inheritance allows a subclass to provide a specific implementation of a method already defined in its superclass.

  3. Duck Typing: In Python, if an object behaves like a certain type (e.g., it has the methods or properties expected of that type), it is treated as that type. This is a dynamic and flexible approach to polymorphism.


Example 1: Polymorphism with a Common Interface


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

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

class Bird:
    def sound(self):
        return "Tweet! Tweet!"

# Function demonstrating polymorphism
def animal_sound(animal):
    print(animal.sound())

# Example usage
dog = Dog()
cat = Cat()
bird = Bird()

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

Here’s an example demonstrating polymorphism using a common method in different classes:


Here, the animal_sound function takes an object as an argument and calls its sound method. Regardless of the object's class, the function behaves appropriately.

Example 2: Polymorphism in Inheritance (Method Overriding)

Inheritance is a key enabler of polymorphism. Here’s how a method in a base class can be overridden in a subclass:


class Shape:
    def area(self):
        return "Area is not defined for a generic shape."

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Example usage
shapes = [Circle(5), Rectangle(4, 6), Shape()]

for shape in shapes:
    print(f"Area: {shape.area()}")

Output:


Area: 78.5
Area: 24
Area: Area is not defined for a generic shape.


In this example:

  • The Shape class has a general area method.
  • The Circle and Rectangle classes override this method to provide specific implementations.
  • The loop demonstrates polymorphism by treating all objects as instances of the Shape class.

Example 3: Polymorphism with Built-in Functions

Python’s built-in functions such as len() exhibit polymorphism because they work with various types of objects.


print(len("PythonBeeTelugu"))  # Output: 16
print(len([1, 2, 3, 4, 5]))    # Output: 5
print(len({"a": 1, "b": 2}))   # Output: 2


Here, the len() function behaves differently depending on the type of argument provided (string, list, or dictionary).


Example 4: Polymorphism with Duck Typing

In Python, duck typing allows polymorphism without enforcing strict type-checking. Here’s an example:


class PythonTutorial:
    def content(self):
        return "Learn Python at @PythonBeeTelugu!"

class JavaTutorial:
    def content(self):
        return "Learn Java step-by-step."

# Function demonstrating polymorphism
def display_content(resource):
    print(resource.content())

# Example usage
python_tutorial = PythonTutorial()
java_tutorial = JavaTutorial()

display_content(python_tutorial)  # Output: Learn Python at @PythonBeeTelugu!
display_content(java_tutorial)   # Output: Learn Java step-by-step.

In this example:

  • The display_content function relies on the content method, regardless of the object's class.
  • Any object with a content method can be used, demonstrating Python’s dynamic nature.

Advantages of Polymorphism

  1. Code Reusability: Common code can handle different object types, reducing redundancy.
  2. Flexibility: Functions and methods can adapt to varying object types and behaviors.
  3. Scalability: New classes can seamlessly integrate with existing functions.

Conclusion

Polymorphism is a powerful and flexible feature of Python that allows objects of different classes to be treated uniformly, as long as they implement the required behavior. This leads to more modular, maintainable, and scalable code. Whether you're overriding methods in subclasses or leveraging dynamic duck typing, polymorphism enhances the power of Python's object-oriented capabilities.

For more detailed Python tutorials, visit @PythonBeeTelugu on YouTube!

Comments