Concept Flow - Duck typing concept
Object passed to function
Check if object has needed method
Call method
Use result
Duck typing means using an object if it has the needed method or behavior, without checking its exact type.
Jump into concepts and practice - no test required
class Duck: def quack(self): return "Quack!" def make_it_quack(thing): return thing.quack()
| Step | Action | Object Type | Method Called | Result |
|---|---|---|---|---|
| 1 | Pass Duck instance to make_it_quack | Duck | None | None |
| 2 | Check if object has quack method | Duck | quack | Yes |
| 3 | Call quack method | Duck | quack | "Quack!" |
| 4 | Return result | Duck | quack | "Quack!" |
| 5 | Pass string to make_it_quack | str | None | None |
| 6 | Check if object has quack method | str | quack | No |
| 7 | Raise AttributeError | str | quack | Error: 'str' object has no attribute 'quack' |
| Variable | Start | After Step 1 | After Step 5 | Final |
|---|---|---|---|---|
| thing | None | Duck instance | string 'hello' | Depends on call |
Duck typing means using any object that has the needed method. No need to check object type explicitly. If method exists, call it; else error occurs. Python trusts the object's behavior, not its class. This allows flexible and simple code.
duck typing in Python primarily focus on?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.class Bird:
def fly(self):
print('Flying')
class Airplane:
def fly(self):
print('Jet flying')
objects = [Bird(), Airplane()]
for obj in objects:
obj.fly()class Cat:
def meow(self):
print('Meow')
def make_sound(animal):
animal.sound()
make_sound(Cat())animal.sound(), but Cat class has meow(), not sound().animal.sound() to animal.meow() to call the existing method.process(item) that works with any object having a serialize() method. Which approach best uses duck typing to handle objects without serialize() safely?hasattr is a safe way to confirm before calling.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.