Sobes.tech
Junior — Middle

Can you give an example of using polymorphism in Python?

sobes.tech AI

Answer from AI

In Python, polymorphism manifests in the fact that objects of different classes can use the same methods and behave differently. This allows writing code that works uniformly with different types of objects.

Example:

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

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

def make_sound(animal):
    print(animal.sound())

cat = Cat()
dog = Dog()

make_sound(cat)  # Outputs: Meow
make_sound(dog)  # Outputs: Bark

Here, the function make_sound accepts an object of any class that has a sound method and calls it, regardless of the specific object type.

Can you give an example of using polymorphism in… - sobes.tech