Duck Typing

If it walks like a duck...

Interview Relevant: Python philosophy

Duck Typing

"If it walks like a duck and quacks like a duck, it's a duck."

Code Examples

Duck typing in Python.

python
1# Duck typing - behavior over type
2def make_speak(animal):
3    # Don't check type, just call method
4    return animal.speak()
5
6class Dog:
7    def speak(self):
8        return "Woof!"
9
10class Cat:
11    def speak(self):
12        return "Meow!"
13
14class Robot:  # Not an animal, but has speak()
15    def speak(self):
16        return "Beep boop!"
17
18# All work because they have speak()
19for obj in [Dog(), Cat(), Robot()]:
20    print(make_speak(obj))
21
22# EAFP: Easier to Ask Forgiveness than Permission
23try:
24    result = obj.speak()
25except AttributeError:
26    result = "Cannot speak"

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In