Bird
0
0

You want to write a function process(item) that works with any object having a serialize() method. Which approach best uses duck typing to handle objects without serialize() safely?

hard📝 Application Q15 of 15
Python - Polymorphism and Dynamic Behavior
You want to write a function process(item) that works with any object having a serialize() method. Which approach best uses duck typing to handle objects without serialize() safely?
ACheck if <code>type(item) == Serializer</code> before calling <code>serialize()</code>
BUse <code>if hasattr(item, 'serialize'):</code> before calling <code>item.serialize()</code>
CWrap <code>item.serialize()</code> call in try-except to catch AttributeError
DDefine a base class with serialize() and inherit all objects from it
Step-by-Step Solution
Solution:
  1. Step 1: Understand duck typing safety

    Duck typing uses behavior, so checking method presence with hasattr is a safe way to confirm before calling.
  2. Step 2: Compare options for best practice

    Use if hasattr(item, 'serialize'): before calling item.serialize() checks method presence explicitly, fitting duck typing. Wrap item.serialize() call in try-except to catch AttributeError uses try-except but is less clear and may hide other errors. Check if type(item) == Serializer before calling serialize() checks type, which is not duck typing. Define a base class with serialize() and inherit all objects from it requires inheritance, reducing flexibility.
  3. Final Answer:

    Use if hasattr(item, 'serialize') before calling item.serialize() -> Option B
  4. Quick Check:

    hasattr check = safe duck typing [OK]
Quick Trick: Check method presence with hasattr before calling [OK]
Common Mistakes:
  • Using type checks instead of behavior checks
  • Ignoring method presence and causing errors
  • Overusing try-except hiding bugs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes