Polymorphism in Python

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables the same operation to behave differently on different classes, promoting flexibility and extensibility in code.


Types of Polymorphism in Python

  1. Compile-Time Polymorphism (Method Overloading):
    • Python does not natively support method overloading as seen in languages like Java or C++.
    • Instead, you can achieve similar behavior by using default arguments or handling arguments dynamically within a single method.
  2. Run-Time Polymorphism (Method Overriding):
    • Achieved through inheritance, where a child class overrides a method from the parent class.
  3. Duck Typing:
    • A Python-specific approach where the object’s behavior is determined by its methods and properties, not its actual class.

Examples of Polymorphism

1. Polymorphism Through Method Overloading

Python does not support traditional method overloading directly, but similar behavior can be implemented using default or variable-length arguments.

class MathOperations:
    def add(self, a, b=0, c=0):
        return a + b + c

math_op = MathOperations()
print(math_op.add(10))        # Output: 10
print(math_op.add(10, 20))    # Output: 30
print(math_op.add(10, 20, 30))  # Output: 60

2. Polymorphism Through Method Overriding

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its parent class.

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

class Dog(Animal):
    def sound(self):
        return "Bark"

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

# Demonstrating polymorphism
animals = [Animal(), Dog(), Cat()]
for animal in animals:
    print(animal.sound())

Output:

Some generic sound
Bark
Meow

3. Polymorphism with Duck Typing

In Python, if an object implements certain methods, it is treated as a valid type for those methods, regardless of the object’s class.

class Bird:
    def fly(self):
        return "Bird can fly"

class Plane:
    def fly(self):
        return "Plane can fly"

class Car:
    def drive(self):
        return "Car can drive"

# Polymorphism using Duck Typing
def can_it_fly(obj):
    return obj.fly() if hasattr(obj, "fly") else "Cannot fly"

print(can_it_fly(Bird()))   # Output: Bird can fly
print(can_it_fly(Plane()))  # Output: Plane can fly
print(can_it_fly(Car()))    # Output: Cannot fly

4. Operator Overloading

Python allows polymorphism by enabling operators like +, -, *, etc., to work differently based on the operands.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2  # Uses __add__
print(p3)     # Output: (4, 6)

5. Polymorphism with Built-In Functions

Built-in Python functions like len() exhibit polymorphism as they can work with different data types.

print(len("hello"))  # Output: 5 (works on a string)
print(len([1, 2, 3]))  # Output: 3 (works on a list)
print(len({"a": 1, "b": 2}))  # Output: 2 (works on a dictionary)

Advantages of Polymorphism

  1. Code Reusability:
    • Write a generic function or class that works with multiple types.
  2. Flexibility:
    • Extend and modify existing code without altering its structure.
  3. Improved Readability:
    • Methods behave differently depending on their context, making code intuitive.

Real-World Use Cases

File Handling: Multiple file types (e.g., .txt, .csv) can be processed using the same interface.

class TextFile:
    def open(self):
        return "Opening a text file"

class CSVFile:
    def open(self):
        return "Opening a CSV file"

files = [TextFile(), CSVFile()]
for file in files:
    print(file.open())

GUI Frameworks: Widgets like buttons, labels, or text fields can implement a common interface (render()), while the rendering behavior differs for each widget type.

class Shape:
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

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

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

# Polymorphism
shapes = [Square(4), Circle(5)]
for shape in shapes:
    print(shape.area())

# Method Overriding
square = Square(4)
print(square.area())  # Output: 16

Polymorphism in Python is highly flexible and can be achieved through method overriding, duck typing, operator overloading, and the use of built-in polymorphic functions. Its application enhances modularity and simplifies complex software development tasks.


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 4 of 7 ): « Previous123 4 567Next »

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading