Polymorphism and duck-typing

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 determined at runtime, is the cornerstone of Python’s object system. This is different from many statically typed languages where a compiler determines if an object can be used. In particular, it means that an object's suitability is not based on inheritance hierarchies, base classes, or anything except the attributes an object has at the time of use.

This is in stark contrast to languages such as Java which depend on what is called nominal sub-typing through inheritance from base classes and interfaces. We'll talk more about inheritance in the context of Python shortly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset