Junior — Middle
Can duck typing be considered a form of polymorphism in Python?
sobes.tech AI
Answer from AI
Yes, duck typing can be considered a form of polymorphism in Python. Unlike classical inheritance-based polymorphism, duck typing is characterized by an object's ability to behave as a certain type if it implements the necessary methods or properties, regardless of its actual class.
For example, if an object has a quack() method, it can be used as a "duck" without type checking:
class Duck:
def quack(self):
print("Quack")
class Person:
def quack(self):
print("I can quack like a duck")
def make_it_quack(duck_like):
duck_like.quack()
make_it_quack(Duck())
make_it_quack(Person())
This demonstrates that the type of the object is not important, but rather the presence of the required interface — the essence of duck typing and polymorphism in Python.