Bird
Raised Fist0

Which code snippet below best illustrates the concept of duck typing in Python?

easy📝 Syntax Q3 of Q15
Python - Polymorphism and Dynamic Behavior
Which code snippet below best illustrates the concept of duck typing in Python?
A<pre>class Writer: def write(self): print('Writing') perform_action = lambda obj: obj.write() if hasattr(obj, 'write') else None perform_action(Writer())</pre>
B<pre>class Writer: def write(self): print('Writing') def perform_action(obj): if isinstance(obj, Writer): obj.write()</pre>
C<pre>class Writer: def write(self): print('Writing') def perform_action(obj): obj.write() perform_action(Writer())</pre>
D<pre>class Writer: def write(self): print('Writing') perform_action = lambda obj: obj.write() if type(obj) == Writer else None perform_action(Writer())</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand duck typing

    Duck typing means an object's suitability is determined by the presence of methods/attributes, not its type.
  2. Step 2: Analyze options

    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.
  3. Final Answer:

    class Writer:
        def write(self):
            print('Writing')
    
    def perform_action(obj):
        obj.write()
    
    perform_action(Writer())
    best demonstrates duck typing.
  4. Quick Check:

    Direct method call without type checks [OK]
Quick Trick: Duck typing calls methods directly without type checks [OK]
Common Mistakes:
MISTAKES
  • Confusing duck typing with explicit type checks
  • Using isinstance() or type() instead of method presence
  • Assuming hasattr() is always duck typing without direct calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes