Member-only story
Duck typing in Python
Duck typing in Python is a programming style that does not look at an object’s type to determine if it has the right interface; instead, it checks whether the object has certain methods and properties. The term comes from the phrase “If it looks like a duck and quacks like a duck, it must be a duck.” In programming, this means that the suitability of an object is determined by the presence of certain methods and properties, rather than the actual type of the object.
Key Concepts of Duck Typing
- Method and Property Checks: Duck typing emphasizes capabilities over actual types, focusing on what an object can do, not what it is.
- Flexibility and Interchangeability: This approach allows for more flexible and interchangeable code. Functions and methods can operate on any object that meets the method signature and property expectation, regardless of the object’s class.
Example: Implementing Duck Typing
Let’s illustrate duck typing with an example involving different classes that are used interchangeably because they implement the same methods.
Define Classes with the Same Method
class Duck:
def quack(self):
print("Quack, quack!")
class Person:
def quack(self):
print("A…