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.
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.