Member-only story
Have you ever heard of duck typing? If not, don’t worry — it doesn’t have anything to do with actual ducks! Instead, duck typing is a programming concept used in dynamic languages like Python. It means that an object’s suitability is determined by the presence of certain methods or attributes rather than the type of the object itself.
In other words, if it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck. Similarly, in Python, if an object behaves like a particular type should behave, then it can be treated as that type, regardless of its actual class. This approach allows for greater flexibility and simplifies coding.
Let’s look at some practical examples to understand how duck typing works in Python.
Example 1: Length Method
One common example of duck typing is when working with sequences such as lists, tuples, and strings. Although they are different types, we can use the len()
function on all of them because they share a common behavior: they implement the length method, which returns the number of elements in the sequence. Here's an example: