KEMBAR78
Duck Typing Python Summary | PDF
0% found this document useful (0 votes)
0 views6 pages

Duck Typing Python Summary

Duck Typing in Python allows objects to be treated based on their behavior rather than their actual type, promoting flexibility and polymorphism. Unlike static typing, Python's dynamic typing enables functions to handle multiple types without the need for overloads. A code example illustrates that methods must be implemented for an object to be treated as a specific type, highlighting that behavior is more important than class type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views6 pages

Duck Typing Python Summary

Duck Typing in Python allows objects to be treated based on their behavior rather than their actual type, promoting flexibility and polymorphism. Unlike static typing, Python's dynamic typing enables functions to handle multiple types without the need for overloads. A code example illustrates that methods must be implemented for an object to be treated as a specific type, highlighting that behavior is more important than class type.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

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.

You might also like