Polymorphism in Collections

Polymorphism in collections refers to using different object types that implement a common interface within a single collection, such as a list or a set. This allows for flexible and reusable code, as operations can be performed on various objects without knowing their exact types.

Key Concepts

  1. Unified Interface: Objects in the collection share a common interface or base class.
  2. Dynamic Behavior: Each object can have its own implementation of the interface methods.
  3. Iterative Processing: Collections can be iterated over, invoking polymorphic methods on each element.

Example of Polymorphism in Collections

Defining Classes

class Animal:
    def speak(self):
        pass

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

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

class Bird(Animal):
    def speak(self):
        return "Tweet!"

Using Polymorphism in a Collection

animals = [Dog(), Cat(), Bird()]

for animal in animals:
    print(animal.speak())

Output

Woof!
Meow!
Tweet!

How It Works

  • Common Interface: Each class (Dog, Cat, Bird) inherits from Animal and implements the speak method.
  • Collection: A list of Animal objects is created.
  • Iteration: Each object’s speak method is called, demonstrating polymorphism.

Example: Shape Collection

class Shape:
    def area(self):
        pass

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

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

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

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

shapes = [Circle(5), Square(4)]

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

Output

Area: 78.5
Area: 16