Generic programming Python

Polymorphism

Polymorphism enables one interface to implement different functions. In other words, one function may accept multiple types of classes.

Example in Python

A function that simulates the response of an organism to a stimulus could operate on any object that implements a respond_to_stimulus method, whether it’s a plant cell or an animal cell.

def simulate_response(cell: Cell):
    cell.respond_to_stimulus()

class PlantCell(Cell):
    def respond_to_stimulus(self):
        # Plant-specific stimulus response

class AnimalCell(Cell):
    def respond_to_stimulus(self):
        # Animal-specific stimulus response

# Both PlantCell and AnimalCell can be passed to simulate_response

Another example with mammals. One class has several child-classes and one function takes the super class as argument.

class Animal:
    def speak(self):
        pass

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

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

def animal_sound(animal):
    print(animal.speak())

# Both Dog and Cat are treated as Animal
animal_sound(Dog())  # Output: Woof!
animal_sound(Cat())  # Output: Meow!