Duck Typing in Python
Summary from Jenny's Lectures CS/IT
- #lec103
What is Duck Typing?
• Based on the phrase: "If it walks like a duck,
swims like a duck, and quacks like a duck, it
probably is a duck."
• Python cares about behavior, not the actual
type or class.
• If an object implements required methods, it
can be treated like the expected type.
• Used to achieve polymorphism in Python.
Static Typing vs Dynamic Typing
• Static Typing (e.g., Java, C): Specify data types
at compile-time.
• Dynamic Typing (Python): Data types are
determined at run-time.
• Python allows functions to handle multiple
types without overloads.
• Duck Typing works due to Python’s dynamic
nature.
Code Example: Duck Typing
• Classes: Duck, Dog, and Person (only Duck and
Dog have swim and speaks methods).
• Function `display(obj)` calls obj.swim() and
obj.speaks().
• Works for Duck and Dog objects.
• Fails for Person because it lacks swim()
method.
Output and Behavior
• Duck object: ✔️Works – prints swim and
quack.
• Dog object: ✔️Works – prints swim and woof.
• Person object: ❌ Fails – "AttributeError: no
swim method".
• Conclusion: Class type doesn’t matter,
behavior does.
Conclusion
• Duck Typing promotes flexibility and
reusability.
• Supports polymorphism without inheritance.
• Python is dynamically typed – enabling Duck
Typing.
• Coming up next: Operator Overloading in
Python.