Polymorphism in Python: Examples with Classes and Functions

Polymorphism in Python means one function, method, or operator works correctly with objects of different types. Python handles this at runtime through duck typing and method overriding. You write a single piece of code, pass in different objects, and Python calls the right behaviour for each one automatically, without any type declarations.

  • Key Takeaway 1: Polymorphism lets one interface serve many data types, reducing duplicate code across your projects.
  • Key Takeaway 2: Python’s duck typing means the interpreter checks behaviour at runtime, not the object’s declared class.
  • Key Takeaway 3: Method overriding in subclasses is the most common form of polymorphism in Python OOP.
  • Key Takeaway 4: Operator overloading uses dunder (double underscore) methods like __add__ to redefine what + does for custom classes.
  • Key Takeaway 5: Python does not support true method overloading by signature, but you can replicate it cleanly with default arguments.

Polymorphism in Python Explained

The word polymorphism comes from Greek, meaning “many forms.” In programming, it describes the ability of different objects to respond to the same method call in their own way. Python bakes this directly into the language design, so you don’t need interfaces or abstract types to get started, unlike Java or C++.

Consider the built-in len() function. Call len("hello") and you get 5. Call len([1, 2, 3]) and you get 3. The function name is the same, the objects are completely different, and Python handles the rest. According to the Python 3 Data Model documentation, this works because each built-in type implements a __len__ dunder method that len() calls internally.

This is the Pythonic angle that separates polymorphism in Python from other languages: you write general code and trust that objects will behave correctly. BTech and BCA students in India often ask why Python feels less rigid than Java, and polymorphism in Python is a big part of the answer. If you’re just getting started, read our guide on how to write and run a Python program before going deeper here.

Types of Polymorphism in Python

There are three main types of polymorphism in Python that every developer should understand:

  • Subtype polymorphism (method overriding): A subclass provides its own version of a method defined in the parent class. This is the most common form in Python OOP.
  • Ad-hoc polymorphism (operator overloading): The same operator behaves differently depending on the types of its operands. Python achieves this through dunder methods.
  • Parametric polymorphism (duck typing): A function works with any type that supports the required operations, without checking the type explicitly.

A Simple Polymorphism in Python Example

Here’s a classic polymorphism in Python example with two classes sharing the same method name:

  • Class Dog has a method speak() that returns "Woof".
  • Class Cat has a method speak() that returns "Meow".
  • A loop iterates over a list containing both a Dog and a Cat object and calls speak() on each.

The loop doesn’t care what type each object is. It calls speak() and gets the right result. That’s runtime polymorphism in Python in action, no type checking needed.

How Polymorphism in Python Compares to Other Languages

Feature Python Java C++
Type checking Runtime (dynamic) Compile-time (static) Both
Method overloading Not natively (use defaults) Yes Yes
Method overriding Yes Yes Yes (virtual)
Duck typing Yes (core feature) No No
Operator overloading Yes (dunder methods) No Yes

The Stack Overflow Developer Survey 2024 ranked Python as the most commonly used programming language for the third consecutive year, with 51% of all respondents using it. Its dynamic type system, which enables duck typing and runtime polymorphism in Python, is a major reason developers find it productive. According to the JetBrains State of Developer Ecosystem 2023, 59% of Python developers use object-oriented programming features, including polymorphism, as a core part of their daily workflow.

Duck Typing and Polymorphism in Python

Duck typing is the principle that says: if it walks like a duck and quacks like a duck, treat it as a duck. Python doesn’t check what class an object belongs to before calling a method. It just tries to call the method, and if the object supports it, everything works.

In practice, this means you can write a function make_it_speak(animal) that calls animal.speak(), and pass it a Dog, a Cat, or even a Parrot class you define next week. The function works with all of them without any modification. This is fundamentally different from Java, where you’d need a shared interface or superclass.

Duck Typing in Real Projects

Python’s data science ecosystem depends on duck typing. When you use Pandas and NumPy, functions often accept any array-like object, whether it’s a Python list, a NumPy array, or a Pandas Series. The function doesn’t care about the type; it cares about whether the object supports the required operations.

A common mistake beginners make is writing unnecessary isinstance() checks to guard every function. Experienced Python developers avoid this unless they genuinely need to branch on type. Defensive isinstance() checks fight against duck typing and make your code harder to extend later.

When Duck Typing Can Bite You

Duck typing shifts error detection to runtime. If you pass an object that doesn’t support the expected method, you’ll get an AttributeError when the code runs, not when you write it. This is why writing unit tests is non-negotiable in Python projects, especially for teams building Python automation, web scraping, and API tools where incorrect types can silently corrupt data.

Method Overriding: Runtime Polymorphism in Python

Method overriding happens when a subclass defines a method with the same name as one in its parent class. When you call that method on a subclass object, Python uses the subclass version, not the parent’s. This is the most common form of polymorphism in Python OOP and the primary mechanism behind runtime polymorphism in Python.

Imagine you’re building a payment gateway integration for an Indian e-commerce platform. You have a base class PaymentMethod with a method process_payment(amount). Subclasses for UPIPayment, NetBanking, and CardPayment each override process_payment() with their own logic. The rest of your application just calls payment.process_payment(500) on whatever object it receives. This pattern is widely used in Indian fintech applications built on Python, from UPI integrations to RBI-compliant payment systems.

The Difference Between Method Overriding and Method Overloading in Python

This is one of the most searched questions on this topic, so it’s worth being direct. Method overriding means a subclass replaces a parent class method with its own version at runtime. Method overloading means defining the same method multiple times with different parameter signatures. Python supports overriding natively. Python does not support traditional overloading: if you define a method twice, the second definition replaces the first. The Pythonic workaround is to use default parameter values or *args and **kwargs inside a single method definition.

Using super() with Overriding

A practical tip that trips up many students: when you override a method, you can still call the parent’s version using super(). This is useful when the child class needs to extend behaviour rather than replace it entirely. Forgetting super().__init__() in a subclass constructor is one of the most common bugs in beginner Python OOP code.

Abstract Base Classes

Python’s abc module lets you define abstract methods that subclasses must override. If a subclass doesn’t implement every abstract method, Python raises a TypeError when you try to instantiate it. This gives you a safety net without losing Python’s flexibility. The official Python abc documentation covers this in full detail.

Understanding inheritance and overriding is core to BSc Computer Science subjects across Indian universities and comes up constantly in technical interviews at Indian IT companies like TCS, Infosys, and Wipro. Getting this right is worth the time.

Operator Overloading: Ad-Hoc Polymorphism in Python

Operator overloading lets you define what standard Python operators like +, -, *, and == do when applied to objects of your own classes. You do this by implementing dunder methods, which are methods with double underscores on both sides of the name. This form of polymorphism in Python is sometimes called ad-hoc polymorphism.

The most used one is __add__. When Python evaluates a + b, it calls a.__add__(b) under the hood. If your class defines __add__, you control what + means for your objects. A Vector class in a physics simulation might add two vectors component by component. A Cart class in a shopping app might merge two cart objects.

Common Dunder Methods for Operator Overloading

Operator Dunder Method Example Use Case
+ __add__ Combine two Vector objects
- __sub__ Subtract one Price from another
* __mul__ Scale a Matrix by a scalar
== __eq__ Compare two Student records by roll number
len() __len__ Return the size of a custom collection
str() __str__ Print a readable representation of an object

One real-world insight: the __eq__ method matters more than beginners realise. If you define it without also defining __hash__, Python sets __hash__ to None, which makes your objects unhashable. You can’t store them in sets or use them as dictionary keys. This is a subtle bug that surfaces only in production, so define both together.

Operator Overloading and AI/ML Libraries

Libraries like NumPy use operator overloading extensively. When you write array1 + array2, NumPy’s __add__ performs element-wise addition across potentially millions of values. This is the same polymorphism in Python mechanism you can use in your own classes. Understanding dunder methods makes you a much better consumer of these libraries, which matters if you’re heading toward a career as an AI engineer. According to NASSCOM’s India Tech Talent Report 2023, Python is the primary language used by over 70% of AI and data science professionals in India, making a solid grasp of polymorphism in Python directly relevant to the Indian job market.

Python’s TIOBE Index ranking has held in the top 2 languages since 2022, and operator overloading is part of why it’s the default choice for data science and machine learning work. The expressiveness it gives library authors trickles down to every developer using those libraries.

Picking the right software development tools goes hand in hand with understanding these language features. Knowing what Python can do natively helps you choose frameworks and libraries that fit your project rather than fighting the language.

Wrapping up: Polymorphism in Python is not a single feature but a cluster of related ideas: duck typing, method overriding, and operator overloading, that together make the language expressive and extensible. Master these three and your Python code gets significantly cleaner and more professional. Here are three things you can do this week:

  1. Write a small class hierarchy with a base class and two subclasses, each overriding a describe() method, then loop over a list of mixed objects and call describe() on each.
  2. Add __add__ and __str__ dunder methods to a custom class (try a Fraction or Vector class) and test them in the Python shell.
  3. Read through Python’s official Data Model page to see the full list of dunder methods available, and pick two you haven’t used yet to experiment with.

Strong programming fundamentals like these are the foundation for more advanced paths in ethical hacking, secure coding, and AI development. If you want to build on this foundation with industry-recognised credentials, explore 3.0 University’s CEH v13 AI online course or browse the full catalogue of 3.0 University online certification courses in Cybersecurity, AI, Blockchain, and Web3.

Frequently Asked Questions

What is polymorphism in Python?

Polymorphism in Python means that a single function, method, or operator can work correctly with objects of different types. Python achieves this at runtime through duck typing and method overriding, so you write one piece of code that handles many types without needing explicit type declarations.

Can you give a polymorphism in Python example?

A clear polymorphism in Python example: create a Dog class and a Cat class, each with a speak() method that returns a different string. Put both objects in a list and loop over it calling speak(). Python calls the correct version for each object automatically. That’s a basic but complete polymorphism in Python example.

What are the types of polymorphism in Python?

The three main types of polymorphism in Python are: subtype polymorphism (method overriding, where a subclass replaces a parent method), ad-hoc polymorphism (operator overloading via dunder methods), and parametric polymorphism (duck typing, where a function works with any object that supports the required operations). Python supports all three natively.

What is the difference between method overriding and method overloading in Python?

Method overriding in Python means a subclass provides its own version of a method defined in the parent class, and Python calls the subclass version at runtime. Method overloading means defining the same method multiple times with different parameter signatures. Python does not support traditional method overloading: the second definition replaces the first. Use default arguments or *args and **kwargs instead.

Does Python support method overloading?

Python does not support traditional method overloading where you define the same method multiple times with different signatures. If you define a method twice, the second definition replaces the first. The Pythonic alternative is to use default parameter values or *args and **kwargs to handle multiple calling patterns inside a single method.

What is duck typing?

Duck typing is Python’s approach to type checking: instead of verifying an object’s class before calling a method, Python simply tries to call the method at runtime. If the object supports it, the call succeeds. If not, you get an AttributeError. The name comes from the idea that if something behaves like a duck, you treat it as one.

What is operator overloading in Python?

Operator overloading in Python means defining dunder methods in your class to control what standard operators do with your objects. Defining __add__ lets the + operator work on your class. Defining __eq__ controls how == compares two instances. This is how libraries like NumPy make mathematical syntax work naturally on custom data structures.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles