Skip to main content

Introduction to Python Polymorphism

Python Polymorphism

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass.

It enables you to write code that can work with objects of different types but perform the appropriate actions based on the specific type of the object.

There are two main forms of polymorphism in Python: method overriding and duck typing.

Method Overriding

Method overriding is a form of polymorphism that occurs when a subclass defines a method with the same name as a method in its superclass.

The subclass's method overrides the implementation of the superclass's method. When the method is called on an object of the subclass, the overridden method in the subclass is executed instead of the superclass's method.

As an example:

class Animal:
def sound(self):
print("Animal makes a sound.")


class Dog(Animal):
def sound(self):
print("Dog barks!")


class Cat(Animal):
def sound(self):
print("Cat meows!")


# Polymorphic behavior
def make_sound(animal):
animal.sound()


dog = Dog()
cat = Cat()

make_sound(dog) # Output: Dog barks!
make_sound(cat) # Output: Cat meows!

In this example:

  • The Animal class defines a sound() method.
  • The Dog and Cat classes inherit from Animal and override the sound() method with their own implementations.
  • The make_sound() function accepts an Animal object as an argument and calls its sound() method.
  • When the make_sound() function is called with a Dog object or a Cat object, the appropriate implementation of the sound() method is executed based on the object's actual type.

Duck Typing

Duck typing is a concept in Python that focuses on the behavior of objects rather than their types.

According to the duck typing principle, "If it walks like a duck and quacks like a duck, then it must be a duck."

In other words, if an object supports a specific set of methods or attributes, it can be considered as having a certain type, regardless of its actual class or inheritance hierarchy.

As an example:

class Duck:
def sound(self):
print("Duck quacks!")


class Car:
def sound(self):
print("Car engine revs!")


# Polymorphic behavior
def make_sound(obj):
obj.sound()


duck = Duck()
car = Car()

make_sound(duck) # Output: Duck quacks!
make_sound(car) # Output: Car engine revs!

In this example:

  • The Duck and Car classes have a sound() method.
  • The make_sound() function takes an object as an argument and calls its sound() method.
  • As long as an object has a sound() method, it can be passed to the make_sound() function, regardless of its specific class.
  • This demonstrates duck typing, where the behavior of the object determines its compatibility with the function, rather than its class or inheritance.