What does the term “duck typing” mean in Python?

What does the term “duck typing” mean in Python?

a) The ability to treat an object based on its behavior rather than its class
b) A way to define types explicitly in Python
c) A method of debugging in Python
d) A form of inheritance used in Python

Answer:

a) The ability to treat an object based on its behavior rather than its class

Explanation:

Duck typing in Python refers to the practice of treating an object according to its behavior (i.e., the methods and properties it implements) rather than its specific class or type. The name comes from the phrase “If it looks like a duck and quacks like a duck, it must be a duck.” In Python, this means you can use any object that provides the required behavior, regardless of its class.

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

class Dog:
    def quack(self):
        return "Woof, but I'm pretending to quack!"

def make_it_quack(duck_like):
    print(duck_like.quack())

# Using duck typing
duck = Duck()
dog = Dog()
make_it_quack(duck)  # Output: Quack!
make_it_quack(dog)   # Output: Woof, but I'm pretending to quack!

In this example, both Duck and Dog classes have a quack() method. The function make_it_quack() accepts any object that implements a quack() method, demonstrating duck typing.

Duck typing is a powerful feature of Python that emphasizes behavior over type, allowing for more flexible and polymorphic code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top