0% found this document useful (0 votes)
5 views10 pages

Understanding Duck Typing in Python

The document discusses Duck Typing in Python, which emphasizes behavior over type, allowing for greater flexibility and reusability in code. It contrasts static and dynamic typing, illustrating Duck Typing through examples and real-life analogies. Key points highlight the importance of behavior in functions and the potential for AttributeErrors when methods are missing.
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)
5 views10 pages

Understanding Duck Typing in Python

The document discusses Duck Typing in Python, which emphasizes behavior over type, allowing for greater flexibility and reusability in code. It contrasts static and dynamic typing, illustrating Duck Typing through examples and real-life analogies. Key points highlight the importance of behavior in functions and the potential for AttributeErrors when methods are missing.
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

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?

You might also like