Sobes.tech
Junior — Middle

Can you tell about cases of applying the principle of polymorphism in your projects?

sobes.tech AI

Answer from AI

In my Python projects, the principle of polymorphism was often used when working with different types of objects that implement the same interface or methods. For example, I had a class Animal with a method speak(), and subclasses Dog and Cat implemented this method in their own way. Thanks to polymorphism, I could write functions that accept objects of type Animal and call speak(), without worrying about the specific type:

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: Animal):
    print(animal.speak())

animal_sound(Dog())  # Outputs: Woof
animal_sound(Cat())  # Outputs: Meow

This simplified code extension and support, allowing the addition of new classes with the desired behavior without changing existing code.