Junior — Middle
Is polymorphism in Python based on the duck typing concept?
sobes.tech AI
Answer from AI
Yes, polymorphism in Python is largely based on the concept of duck typing. This means that in Python, the type of an object is not as important as the presence of certain methods and properties that are necessary to perform an operation. For example, if an object "quacks" and "walks like a duck," Python will allow it to be used as a duck, regardless of its actual class.
Example:
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()) # Quack
make_it_quack(Person()) # I can quack like a duck
Here, the function make_it_quack does not check the type of the object but simply calls the quack method. This is an example of polymorphism through duck typing.