Introducing duck typing in Python
Duck typing, sometimes referred to as dynamic typing, is mostly adopted in programming languages that support dynamic typing, such as Python and JavaScript. The name duck typing is borrowed based on the following quote:
"If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck."
This means that if a bird is behaving like a duck, it will likely be a duck. The point of mentioning this quote is that it is possible to identify an object by its behavior, which is the core principle of duck typing in Python.
In duck typing, the type of class of an object is less important than the method (behavior) it defines. Using duck typing, the types of the object are not checked, but the method that is expected is executed.
To illustrate this concept, we take a simple example with three classes, Car
, Cycle
, and Horse
, and we try to implement a start
method in each of them. In the Horse
class, instead...