Duck Typing in Python

Duck Typing in Python

In my recent exploration of Python's object-oriented programming, I've learned about a concept called duck typing which is a way to implement polymorphism in python without inheritance.

What is Duck Typing?

So in python we say when an object quacks like a duck, swims like a duck, eats like a duck or simply acts like a duck, that object is a duck.

It extends the concept of dynamic tying in Python, which means we can change the type of an object at any statement in the code. See the code below to understand

x = 5 # type is int
print(type(x))

x = "duck" # type is now str
print(type(x))        

Due to the dynamic nature of Python, this code if executed will result in x being 5 as an integer at first and then x as duck which is of type string. Duck typing allows the user to use any object that provides the required behavior without the constraint that it has to be a subclass.

A small implementation of duck typing with class

class Dog:
    def Speak(self):
        print("Woof woof")


class Cat:
    def Speak(self):
        print("Meow meow")


class Animal:
    def Sound(self, animal):
        animal.Speak()


animal = Animal()
dog = Dog()
cat = Cat()

animal.Sound(dog)
animal.Sound(cat)        

In the above implementation, based on the concept of duck typing, the animal object does not matter in the Sound, as long has the associated behavior Speak defined in the object's class definition. In layman terms, since both the animals, dog and cat can speak like animal they both are animals.

This is how polymorphism can be achieved without inheritance in python.


To view or add a comment, sign in

More articles by Sayanjit Das

  • How to integrate Tailwindcss with Flask

    As a Python web developer, you're likely familiar with web frameworks like Flask. If not, don't worry this article…

  • List is not an Iterator

    We have probably been using list since we started programming in Python, but we may not have realized it is not…

  • EAFP in Python: Leveraging importlib for Graceful Module Import Checks

    Python, as a dynamic and versatile programming language, is known for its simplicity and readability. One of the…

  • Advent of Database system

    Over the past few decades, the management of data within computers has undergone significant transformation. While we…

    1 Comment
  • Sort in pythonic way

    Sorting data is a fundamental operation in programming, and Python offers a powerful built-in function to accomplish…

  • Association of objects in python

    As per my last article on relationships between objects in python we learned that in object-oriented programming…

  • Relation between objects in Python

    Inheritance is a way to represent relationships between classes which we also refer to as is-a relationship. Let me…

Explore content categories