Thursday, 6 March 2025

Polymorphism in Python

Polymorphism in Python

Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated uniformly. It enables a single interface to represent different underlying forms (data types), enhancing code flexibility and reusability.


Why Use Polymorphism?

  1. Code Reusability: Allows methods to work with different types of objects.
  2. Simplified Code: Reduces the need for complex if-else or type-checking statements.
  3. Flexibility: Supports dynamic behavior in programming.
  4. Extensibility: Allows adding new classes with minimal changes to existing code.

Types of Polymorphism in Python

  1. Compile-Time Polymorphism (Method Overloading)
  2. Run-Time Polymorphism (Method Overriding)
  3. Polymorphism with Functions and Objects
  4. Polymorphism with Class Methods
  5. Polymorphism with Inheritance

1. Compile-Time Polymorphism (Method Overloading)

Python does not directly support method overloading like other languages (e.g., Java). However, you can achieve similar behavior using default parameters or *args and **kwargs.


class MathOperations: # Single method handling multiple types of parameters def add(self, a=None, b=None, c=None): if a is not None and b is not None and c is not None: return a + b + c elif a is not None and b is not None: return a + b else: return a math = MathOperations() print(math.add(5, 10)) # Output: 15 print(math.add(5, 10, 15)) # Output: 30

Key Points:

  • Python does not support true method overloading, but you can use default arguments.
  • This approach mimics method overloading by providing flexibility in parameter handling.

2. Run-Time Polymorphism (Method Overriding)

When a child class provides a specific implementation of a method that is already defined in its parent class.


class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks") class Cat(Animal): def sound(self): print("Cat meows") # Demonstrating polymorphism animals = [Animal(), Dog(), Cat()] for animal in animals: animal.sound()

Output:


Animal makes a sound Dog barks Cat meows

Key Points:

  • Method overriding enables dynamic polymorphism.
  • The method to call is determined at runtime based on the object type.

3. Polymorphism with Functions and Objects

Built-in functions like len() demonstrate polymorphism by working with different data types.


print(len("Hello")) # Output: 5 (string) print(len([1, 2, 3])) # Output: 3 (list) print(len((10, 20))) # Output: 2 (tuple)

Key Points:

  • The len() function works with multiple data types.
  • The behavior of len() is consistent but adapts to the data type.

4. Polymorphism with Class Methods

You can create polymorphic behavior by defining methods with the same name in different classes.


class Rectangle: def area(self, length, width): return length * width class Circle: def area(self, radius): return 3.14 * radius * radius # Polymorphism with class methods shapes = [Rectangle(), Circle()] for shape in shapes: if isinstance(shape, Rectangle): print("Area of Rectangle:", shape.area(5, 3)) # Output: 15 elif isinstance(shape, Circle): print("Area of Circle:", shape.area(4)) # Output: 50.24

Key Points:

  • The same method name (area) is used in different classes.
  • The specific method called depends on the object type.

5. Polymorphism with Inheritance


class Bird: def fly(self): print("Bird can fly") class Sparrow(Bird): def fly(self): print("Sparrow flies fast") class Ostrich(Bird): def fly(self): print("Ostrich can't fly") # Demonstrating polymorphism with inheritance for bird in [Bird(), Sparrow(), Ostrich()]: bird.fly()

Output:


Bird can fly Sparrow flies fast Ostrich can't fly

Key Points:

  • The fly() method is overridden in subclasses.
  • Polymorphism allows the appropriate method to be called at runtime.

Polymorphism with Abstract Classes

Abstract classes use polymorphism by defining abstract methods that are implemented differently in subclasses.


from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): print("Dog barks") class Cat(Animal): def make_sound(self): print("Cat meows") # Polymorphism with abstract class for animal in [Dog(), Cat()]: animal.make_sound()

Output:


Dog barks Cat meows

Key Points:

  • Abstract classes enforce method implementation in derived classes.
  • Supports polymorphic behavior through abstract methods.

Polymorphism with Operator Overloading

You can override special methods to change the behavior of operators for user-defined objects.


class Point: def __init__(self, x, y): self.x = x self.y = y # Overloading the + operator def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" point1 = Point(1, 2) point2 = Point(3, 4) # Using + on Point objects result = point1 + point2 print(result) # Output: (4, 6)

Key Points:

  • Operator overloading uses special methods like __add__, __str__, etc.
  • Enables polymorphic behavior with built-in operators.

Best Practices for Polymorphism

  1. Use Method Overriding: Promote dynamic polymorphism with method overriding.
  2. Leverage Abstract Classes: Use abstract base classes (ABC) to enforce polymorphism.
  3. Avoid Excessive Type Checks: Minimize isinstance() and type() checks.
  4. Design for Extensibility: Create methods that work with multiple object types.
  5. Keep Code Readable: Avoid complex polymorphic structures that reduce code clarity.

When to Use Polymorphism:

  • When different classes share a common interface.
  • When the exact class type is not important.
  • When you want to define methods that can operate on any object.

Conclusion:

Polymorphism enhances flexibility and maintainability in Python programming. By allowing different objects to respond to the same method call, polymorphism supports cleaner code and reduces dependencies.

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...