Duck Typing in Python
Sobana S
Introduction
• Definition of Duck Typing
• Connection to polymorphism
• Agenda of the talk
What is Duck Typing?
• If it walks like a duck and quacks like a duck →
treat it as a duck
• Focus on behavior, not type
• Possible due to dynamic typing
Static vs Dynamic Typing
• Static typing: C, Java → declare types before
use
• Dynamic typing: Python infers type at runtime
• Duck Typing builds on dynamic typing
Example: Duck, Dog, and Person
• Classes with swim() and speaks() methods
• Function display(obj) works if methods exist
• Demonstrates Duck Typing in action
What if a Method is Missing?
• If swim() is missing in Person
• AttributeError occurs
• Behavior matters more than class name
Real-Life Analogy
• Rahul behaves like an innocent boy
• People judge based on behavior
• Same idea in Duck Typing
Why is Duck Typing Useful?
• Code flexibility and reusability
• No strict inheritance needed
• Simplifies polymorphism
• Supports loose coupling
Key Points to Remember
• Python is dynamically typed
• Duck Typing possible due to this
• Functions rely on behavior, not type
• Missing methods cause AttributeError
• No need for inheritance if behavior matches
Conclusion
• Duck Typing promotes simplicity and flexibility
• Polymorphism without strict hierarchies
• Behavior matters more than type
• Thank you! Questions?