ATHENA
Python for Intermediate Learners / Smart Reader
THE ATHENA LIBRARY

Python for Intermediate Learners

Daniel Haile · textbook

Chapter 7 · Duck Typing and Polymorphism

If it quacks like a duck

Python practises polymorphism without demanding a shared parent class. A function that calls item.area() works with any object that provides an area method. This is duck typing: behaviour matters more than declared type.

Method overriding still matters. When a Circle subclass overrides Shape.area(), a loop over mixed shapes calls each object's own version — exactly the dynamic dispatch Java programmers know. The difference is that Python checks for the method at runtime rather than at compile time.

For clearer contracts, typing.Protocol and abc.ABC let you describe the interface you expect. Protocols bring Python close to Java interfaces, while keeping the flexibility that makes duck typing so expressive.

Polymorphism in Python asks one question: can this object do what I need?

Fictional educational sample written for the Athena demo · Page 118 of 356.

100%saved