Bird
0
0

Which of the following Python code snippets correctly demonstrates duck typing?

easy📝 Syntax Q12 of 15
Python - Polymorphism and Dynamic Behavior
Which of the following Python code snippets correctly demonstrates duck typing?
Adef quack(duck): if hasattr(duck, 'quack'): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
Bdef quack(duck: Duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
Cdef quack(duck): if type(duck) == Duck: duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
Ddef quack(duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck())
Step-by-Step Solution
Solution:
  1. Step 1: Identify duck typing usage

    Duck typing means using an object if it has the needed method, without checking its type.
  2. Step 2: Analyze each option

    def quack(duck): if hasattr(duck, 'quack'): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck()) uses hasattr to check for method presence, which fits duck typing. Options B and C check type explicitly, which is not duck typing. def quack(duck): duck.quack() class Duck: def quack(self): print('Quack!') quack(Duck()) assumes the object has the method but does not check, which is okay but less safe than A.
  3. Final Answer:

    Using hasattr to check method presence before calling -> Option A
  4. Quick Check:

    hasattr check = duck typing safe use [OK]
Quick Trick: Look for method presence checks, not type checks [OK]
Common Mistakes:
  • Confusing type checking with duck typing
  • Ignoring method presence before calling
  • Assuming duck typing requires no checks at all

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes