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.