0
0
Pythonprogramming~5 mins

Duck typing concept in Python

Choose your learning style9 modes available
Introduction

Duck typing lets you use any object that behaves the way you expect, without worrying about its exact type.

When you want to write flexible functions that work with different kinds of objects.
When you only care if an object has certain methods or properties, not its class.
When you want to avoid strict type checks and focus on behavior.
When working with objects from different libraries that share similar interfaces.
When you want to write simpler and more readable code without explicit type declarations.
Syntax
Python
def function(obj):
    obj.some_method()

# No need to check obj's type, just use its methods

Python does not require you to declare types explicitly.

If the object has the method or attribute used, it works; otherwise, it raises an error.

Examples
Both Duck and Person have a quack method, so make_it_quack works with either.
Python
class Duck:
    def quack(self):
        print("Quack!")

class Person:
    def quack(self):
        print("I'm pretending to be a duck!")

def make_it_quack(thing):
    thing.quack()

make_it_quack(Duck())
make_it_quack(Person())
Dog does not have quack, so calling make_it_quack raises an error.
Python
class Dog:
    def bark(self):
        print("Woof!")

def make_it_quack(thing):
    thing.quack()

make_it_quack(Dog())  # This will cause an error
Sample Program

This program shows duck typing by calling fly() on different objects that both have this method.

Python
class Bird:
    def fly(self):
        print("Flying high!")

class Airplane:
    def fly(self):
        print("Zooming through the sky!")

def let_it_fly(flyer):
    flyer.fly()

bird = Bird()
airplane = Airplane()

let_it_fly(bird)
let_it_fly(airplane)
OutputSuccess
Important Notes

Duck typing focuses on what an object can do, not what it is.

Be careful: if an object lacks the expected method, your program will raise an error.

You can use hasattr() to check if an object has a method before calling it.

Summary

Duck typing means using objects based on their behavior, not their type.

It makes code flexible and easy to reuse with different objects.

Errors happen only if the object does not have the needed methods or properties.