Python - Polymorphism and Dynamic Behavior
Which code snippet below best illustrates the concept of duck typing in Python?
class Writer:
def write(self):
print('Writing')
def perform_action(obj):
obj.write()
perform_action(Writer()) calls obj.write() directly without type checks, relying on the method's presence, which is duck typing.class Writer:
def write(self):
print('Writing')
def perform_action(obj):
if isinstance(obj, Writer):
obj.write() uses isinstance(), which is explicit type checking.class Writer:
def write(self):
print('Writing')
perform_action = lambda obj: obj.write() if hasattr(obj, 'write') else None
perform_action(Writer()) uses hasattr() which is duck typing but wrapped in a lambda and conditional, less direct.class Writer:
def write(self):
print('Writing')
perform_action = lambda obj: obj.write() if type(obj) == Writer else None
perform_action(Writer()) uses type() equality, which is strict type checking.class Writer:
def write(self):
print('Writing')
def perform_action(obj):
obj.write()
perform_action(Writer()) best demonstrates duck typing.15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions