Back to: Python Programming
Duck typing in Python is a programming concept where the type or class of an object is less important than the methods it implements. It derives its name from the saying, “If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”
In Python, this means that if an object behaves in a certain way – specifically, if it has the necessary methods and attributes – it can be treated as a particular type, regardless of its actual class inheritance. Python focuses on the behavior of an object rather than its explicit type.
Here’s an illustration:
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm imitating a duck!")
def make_it_quack(animal):
animal.quack()
# Using duck typing
duck_obj = Duck()
person_obj = Person()
make_it_quack(duck_obj) # Output: Quack!
make_it_quack(person_obj) # Output: I'm imitating a duck!
In this example, the make_it_quack function doesn’t care whether animal is an instance of Duck or Person. It only cares that the object passed to it has a quack() method. If the object has this method, the function will execute successfully. This demonstrates the core principle of duck typing: if an object can perform the required actions, its specific type is irrelevant.
Duck typing is effectively another way to achieve polymorphism besides Inheritance.
Example:
class Animal:
alive = True
class Dog(Animal):
def speak(self):
print("WOOF!")
class Cat(Animal):
def speak(self):
print("MEOW!")
class Car:
alive = False
def speak(self):
print("HONK!")
animals = [Dog(), Cat(), Car()]
for animal in animals:
animal.speak()
print(animal.alive)