Polymorphism is a programming language feature which allows us to use objects of different types through a uniform interface. The concept of polymorphism applies to both functions and more complex objects. We've just seen an example of polymorphism with the card printing example. The make_boarding_card()
method didn't need to know about an actual – or as we say "concrete" – card printing type, only the abstract details of its interface. This interface is essentially just the order of it's arguments. Replacing our console_card_printer
with a putative html_card_printer
would exercise polymorphism.
Polymorphism in Python is achieved through duck typing. Duck typing is in turn named after the "duck test", attributed to James Whitcomb Riley, the American poet:
Figure 8.5: James Whitcomb Riley
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
Duck typing, where an object's fitness for a particular use is only...