[PYTHON] Duck Typing

 [PYTHON] Duck Typing

Duck typing is a type of type checking in Python that involves checking the presence of certain methods and properties rather than the type of object itself. This means that an object can be used as long as it has the required methods and properties, regardless of its actual type.

In Python, duck typing is used to determine the type of an object at runtime, rather than at compile time. This allows for more flexibility in the types of objects that can be used in a given piece of code.

Here is an example of duck typing in Python:

def quack(duck):

class Duck:
    def quack(self):

class Goose:
    def quack(self):

d = Duck()
quack(d)  # Output: "Quack!"

g = Goose()
quack(g)  # Output: "Honk!"

In this example, the quack() function is defined to take an object with a quack() method. When the Duck and Goose classes are defined, they both have a quack() method, so they can be used as arguments to the quack() function. This demonstrates how duck typing allows for objects of different types to be used interchangeably as long as they have the required methods.


Popular posts from this blog

Top 36 effective ways to collaborate with other technology companies or developers to create innovative and high-value products or services

[PYTHON] Top 29 best practices for writing efficient and effective code in 2023

LinkedIn Apply Bot 🤖