[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):
    duck.quack()

class Duck:
    def quack(self):
        print("Quack!")

class Goose:
    def quack(self):
        print("Honk!")

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.

Comments

Boulouma.com

LinkedIn Apply Bot 🤖

From $1 to $500 Empire: How ChatGPT Revolutionized AI Products in 52 Weeks!

[LIVE] Habits - Part 1- The first core component of Masterplan by Amin Boulouma The Systems Builder