Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is duck typing in Python, and how does it relate to polymorphism?

SHORT ANSWER

Duck typing means an object is accepted if it has the methods you call, regardless of its class. It gives polymorphism without a shared parent or interface.

Explain it simply

If it walks like a duck and quacks like a duck, treat it as a duck. A tea stall only cares whether you can pay; it does not ask whether you hold a UPI app, cash or a card.

In Python, a function that calls x.pay() works with any object that has a pay method. No common base class is required.

Example

python
class Upi:
    def pay(self, amt): return f"UPI paid {amt}"

class Cash:
    def pay(self, amt): return f"Cash paid {amt}"

def checkout(method, amt):
    return method.pay(amt)         # only needs a pay() method

print(checkout(Upi(), 120))        # UPI paid 120
print(checkout(Cash(), 80))        # Cash paid 80

If an object lacks pay, you get an AttributeError at runtime. Type hints with Protocol can describe the shape for tools to check.

What to say in the interview

"Duck typing checks behaviour, not declared type: any object with the needed methods works. It gives polymorphism without inheritance, at the cost of errors appearing at runtime unless supported by tests or Protocol type hints."

Common mistakes

  • Assuming Python polymorphism needs a common parent class.

#python#polymorphism#duck-typing

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.