Junior — Middle
How is polymorphism implemented through the duck typing principle in Python?
sobes.tech AI
Answer from AI
In Python, polymorphism is implemented through the principle of duck typing, which means that the type of the object is not important, but rather the presence of the required methods or attributes. If an object behaves like the expected type ("looks like a duck and quacks like a duck"), then it can be used in the appropriate context.
For example, if a function expects an object with a quack() method, it doesn't matter what class it belongs to — as long as this method is implemented:
class Duck:
def quack(self):
print("Quack")
class Person:
def quack(self):
print("I can imitate a duck")
def make_it_quack(duck_like):
duck_like.quack()
make_it_quack(Duck()) # Quack
make_it_quack(Person()) # I can imitate a duck
Thus, polymorphism is achieved not through inheritance, but through interface compatibility of objects.