Polymorphism in Python with Example


Polymorphism in Python with Example might sound like a mouthful, but it’s a handy concept that can really elevate your coding game. At its core, polymorphism is about crafting code that’s flexible and reusable, letting you achieve more with less effort. Fancy creating adaptable and versatile programs that handle different data types seamlessly? You’re in the right place! Stick around as we dive into what polymorphism means, why it’s crucial, and how you can easily implement it in Python.

What is Polymorphism in Python?

Polymorphism is a key concept in object-oriented programming (OOP) that allows objects of different classes to respond to the same method call in different ways. In simple terms, polymorphism means “many forms.” It helps write flexible and reusable code by allowing a single function or method to behave differently based on the object it is acting on.

Polymorphism in Python – Definition

Python achieves polymorphism mostly through method overriding and duck typing. It lets different classes implement the same method name with behavior specific to their type.

Example:

class Bird:
    def fly(self):
        print("Bird is flying")

class Airplane:
    def fly(self):
        print("Airplane is flying")

def lets_fly(obj):
    obj.fly()

lets_fly(Bird())      # Output: Bird is flying
lets_fly(Airplane())  # Output: Airplane is flying

Here, the fly() method behaves differently depending on the object passed, even though it shares the same method name.

Compile-Time vs Runtime Polymorphism

FeatureCompile-Time PolymorphismRuntime Polymorphism
Also Known AsMethod OverloadingMethod Overriding
Binding TypeStatic BindingDynamic Binding
When It’s ResolvedDuring compilationDuring execution
Python SupportNot natively supported in PythonFully supported via inheritance
Example in PythonNot available directlyUsing super() and overriding methods

⚠️ Note on Method Overloading in Python

Traditional method overloading (same method name with different parameters) is not supported in Python like in Java or C++. If you define the same method twice in a class, the last definition will override the previous one.

However, Python supports default arguments and *args/**kwargs to mimic method overloading behavior:

class Calculator:
    def add(self, a, b=0, c=0):
        return a + b + c

calc = Calculator()
print(calc.add(2))         # Output: 2
print(calc.add(2, 3))      # Output: 5
print(calc.add(2, 3, 4))   # Output: 9

This flexibility is a form of “manual overloading” using Python’s dynamic nature, but it’s not true compile-time polymorphism.

Polymorphism Through Inheritance

Python supports polymorphism primarily through inheritance, where a child class inherits methods and properties from a parent class but can also override those methods to provide specific behavior. This allows different objects (from different classes) to respond differently to the same method call — a concept known as runtime polymorphism.

The child class overrides a method that the parent class already defines, providing its own version.

This enables dynamic method dispatch, meaning the method that gets called is determined at runtime based on the actual object type, not the reference type.

Python Code Example: Polymorphism with Inheritance

class Animal:
    def speak(self):
        return "Animal sound"

class Dog(Animal):
    def speak(self):
        return "Bark"

class Cat(Animal):
    def speak(self):
        return "Meow"

for pet in [Dog(), Cat()]:
    print(pet.speak())

Line-by-Line Explanation

class Animal:
    def speak(self):
        return "Animal sound"
  • This is the base class Animal that defines a generic method speak().
  • It returns a default message "Animal sound".
class Dog(Animal):
    def speak(self):
        return "Bark"
  • Dog is a child class of Animal.
  • It overrides the speak() method with its own implementation, returning "Bark".
class Cat(Animal):
    def speak(self):
        return "Meow"
  • Similarly, Cat is another child class that overrides the same speak() method, returning "Meow".
for pet in [Dog(), Cat()]:
    print(pet.speak())
  • Here, we create a list of different objects: one instance of Dog and one of Cat.
  • We loop through the list and call the speak() method on each object.
  • At runtime, Python dynamically decides which speak() method to call based on the actual object (Dog or Cat), not the parent class Animal.

Highlights

  • Method Overriding: The speak() method is defined in the parent class and redefined in each child class with specific behavior.
  • Dynamic Method Dispatch: Python determines which speak() method to invoke at runtime, enabling polymorphic behavior.

This approach helps you write cleaner, more maintainable, and scalable code by leveraging the power of object-oriented design.

Output

Bark
Meow

Polymorphism in Python: Real-Life Applications


  1. Netflix’s Dynamic Content Delivery: Netflix uses polymorphism to display content differently based on the device you’re using. Whether you’re on a smartphone, tablet, or smart TV, the interface adapts seamlessly. Polymorphism helps in writing functions that can process media content in a general way. This means they can deliver content quickly and efficiently, enhancing user experience.

  2. Spotify’s Sound Quality Variability: Spotify employs polymorphism to adjust the audio quality depending on user settings and network capacity. By using polymorphic functions, Spotify can offer the same music piece at different qualities, ensuring listeners enjoy their music without interruptions, regardless of their internet speed.

  3. Amazon’s Product Display Adaptation: When you’re shopping on Amazon, the platform uses polymorphism to show various product formats, customer reviews, and recommendations tailored to your preferences. This customization is handled by polymorphic functions that adapt to different user data types, ensuring an optimized shopping experience.

  4. Uber’s Payment Processing: Uber demonstrates polymorphism by allowing different types of payment methods—credit cards, digital wallets, etc.—through a consistent interface. This is implemented via polymorphic methods that handle distinct payment transactions in a uniform way, simplifying the payment process for users.

Real-Life Use Cases of Polymorphism

Polymorphism is widely used in real-world Python applications to simplify code and make systems more extensible. Here are some practical use cases:

1. GUI Development
In graphical user interfaces, different widgets like buttons, checkboxes, or sliders can have the same method name (e.g., on_click()), but the behavior varies depending on the widget type. The framework calls the appropriate method at runtime based on the specific object.

2. Game Development
In games, characters like a soldier, alien, or robot may all have an attack() method. Although they share the method name, each character implements it differently, enabling diverse in-game behaviors without modifying the main game logic.

3. APIs and Frameworks
Many frameworks allow developers to plug in custom logic by subclassing base classes and overriding methods like process_request() or validate(). The base framework can call these methods polymorphically without knowing the actual implementation.

Common Mistakes to Avoid

While implementing polymorphism in Python, beginners often make the following mistakes:

1. Forgetting to Override Methods
A subclass may unintentionally inherit a method from the parent class without overriding it. This leads to undesired generic behavior instead of the expected specialized action.

2. Misunderstanding Dynamic Dispatch
Developers may assume the method executed is based on the reference type (like in statically typed languages), not realizing Python resolves the method at runtime based on the actual object.

3. Not Using Inheritance Correctly
Trying to implement polymorphism without a proper inheritance structure can result in repetitive code and broken object-oriented design. Subclasses must be meaningfully derived from the parent to support true polymorphic behavior.

Practice Challenge

Task: Create a Shape class and define Circle and Square as subclasses. Override a method named area() in each subclass to compute and return the area of the shape.

Sample Code:

class Shape:
    def area(self):
        return 0

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

shapes = [Circle(5), Square(4)]

for shape in shapes:
    print(f"Area: {shape.area()}")

What You Learn:

  • How to define a base class with a generic method.
  • How to override that method in derived classes.
  • How Python dynamically calls the appropriate method using polymorphism.

Discover our AI-powered python online compiler, where creativity meets technology. Instantly write, run, and test your code with the help of AI, making coding smoother and faster. Say goodbye to long setup times and hello to more productive programming sessions—right from your browser.

Conclusion

Polymorphism in Python with Example is beneficial for mastering dynamic method invocation and enhancing code flexibility. Embracing this concept brings a sense of accomplishment and adaptability to coding challenges. Why not explore more programming languages by visiting Newtum and broaden your horizons in coding today?

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author