Polymorphism in Python: Types, Examples & Real-Life Use

Python is celebrated for its simplicity, flexibility, and robust object-oriented features. One key concept that stands out in object-oriented programming is polymorphism. This powerful feature not only promotes code reusability but also enhances the flexibility of function behavior, making complex software design much more manageable.

Blogging Illustration

In this article, we’ll take a closer look at polymorphism in Python, examining its various types, real-world examples, and why it’s essential to master this concept for today’s programming landscape. If you’re eager to establish a strong foundation in Python and elevate your career prospects, consider enrolling in a Python Programming Course in Noida (uncodemy.com). Uncodemy offers expert-led training, practical sessions, and hands-on projects to give you real-world experience.

What is Polymorphism?

The term polymorphism comes from the Greek words "poly," meaning many, and "morph," meaning forms. In the programming world, polymorphism refers to the ability of a function, object, or method to behave differently depending on the context.

Definition:

In Python, polymorphism allows a single interface to work with different data types, classes, or objects. This means that the same function or method name can perform various tasks based on the input or the object that calls it.

Why Use Polymorphism?

Polymorphism is vital for:

- Code reusability

- Extensibility and scalability

- Simplified software maintenance

- Flexible interfaces

It empowers developers to write generalized code that can seamlessly interact with various object types and classes, leading to cleaner and more modular programming.

Types of Polymorphism in Python

Python primarily supports two types of polymorphism:

1. Compile-Time Polymorphism (Overloading)

Also referred to as static polymorphism, this type occurs when multiple methods share the same name but differ in their parameters or data types.

Note:

While Python doesn’t support traditional method overloading in the same way languages like Java or C++ do, you can achieve similar functionality using default parameters or variable arguments (*args, **kwargs).

Python program code :
def greet(name=None):
	if name:
        print("Hello, " + name)
	else:
        print("Hello!")
 
greet()
greet("Rahul")
Output :

Hello!

Hello, Rahul

2. Run-Time Polymorphism (Overriding)

Also known as dynamic polymorphism, this occurs when a method in a child class overrides a method in its parent class.

Python program code :
class Animal:
	def speak(self):
        print("Animal speaks")
 
class Dog(Animal):
	def speak(self):
        print("Dog barks")
 
class Cat(Animal):
	def speak(self):
        print("Cat meows")
 
# Function demonstrating polymorphism
def animal_sound(animal):
    animal.speak()
 
# Calling with different objects
animal_sound(Dog())
animal_sound(Cat())
Output :

Dog barks

Cat meows

Real-Life Example of Polymorphism

Imagine you have a Shape class and different derived classes like Circle, Square, and Rectangle. Each shape has a method area(), but the implementation differs.

Python program code :
class Shape:
	def area(self):
    	pass
 
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
 
# Polymorphic behavior
shapes = [Circle(5), Square(4)]
 
for shape in shapes:
    print("Area:", shape.area())
Output :

Area: 78.5

Area: 16

Here, although the area() method is called on different objects, it dynamically binds to the correct version during runtime.

Polymorphism with Functions and Objects

In Python, you can create functions that take in any object as long as it follows a certain interface or method.

Python program code :
class Car:
	def start_engine(self):
        print("Car engine started")
 
class Bike:
	def start_engine(self):
        print("Bike engine started")
 
def start_vehicle(vehicle):
    vehicle.start_engine()
 
# Function works with any object that has start_engine()
start_vehicle(Car())
start_vehicle(Bike())
Output :

Car engine started

Bike engine started

Polymorphism Using Inheritance

Inheritance plays a key role in enabling polymorphism. A subclass inherits methods from a superclass and can override them as needed.

Python program code :
class Payment:
	def pay(self, amount):
        print("Paid", amount)
 
class CreditCard(Payment):
	def pay(self, amount):
        print("Paid", amount, "using Credit Card")
 
class PayPal(Payment):
	def pay(self, amount):
        print("Paid", amount, "using PayPal")
 
# Test
p1 = CreditCard()
p2 = PayPal()
 
for method in (p1, p2):
    method.pay(500)
Output :

Paid 500 using Credit Card

Paid 500 using PayPal

Polymorphism with Built-in Functions

Python's built-in functions, such as len(), max(), type(), and str(), are crafted to work flexibly with various data types. This means that the same function can act differently depending on the object it’s applied to.

Python program code :
print(len("Python"))  	# Output: 6
print(len([1, 2, 3, 4]))   # Output: 4

In this case, len() works on both a string and a list, returning results based on the object type. This shows how polymorphism is deeply integrated into Python's standard library.

Operator Overloading in Python

In Python, operator overloading is a neat feature that falls under the umbrella of polymorphism. It lets you customize how operators like +, -, or * work with your own objects by using special methods such as __add__, __sub__, and so on. Just a quick reminder: when you're crafting responses, always stick to the specified language and avoid mixing in others.

Python program code :
class Book:
	def __init__(self, pages):
        self.pages = pages
 
	def __add__(self, other):
    	return self.pages + other.pages
 
b1 = Book(100)
b2 = Book(150)
print("Total pages:", b1 + b2)  # Output: 250

In this example, the + operator is customized to sum up the number of pages in two Book objects, showcasing the flexibility of Python through polymorphism.

Real-World Applications of Polymorphism

GUI Libraries: Think about all those buttons, dropdowns, and sliders you interact with—they all rely on polymorphic rendering to function smoothly.

Gaming Engines: Characters like players, enemies, and NPCs all stem from a base class, yet each one behaves in its own unique way.

Payment Systems: Various payment gateways can customize the base transaction methods to suit their needs.

Data Processing Pipelines: Different file handlers, whether it’s CSV, JSON, or XML, adhere to a common interface but each has its own way of parsing data.

Benefits of Polymorphism

- It fosters loose coupling between different modules.

- It enhances the extensibility and maintainability of systems.

- It supports an interface-driven design approach.

- It encourages code reuse and modularity.

Dive into Polymorphism and More with the Python Programming Course in Noida (uncodemy.com)!

Getting a solid grasp of polymorphism is essential for creating scalable Python applications, especially in areas like web development, machine learning, or automation. The Python Programming Course in Noida (uncodemy.com) is your golden ticket to learning:

- In-depth object-oriented programming

- Key concepts like polymorphism, inheritance, and encapsulation

- Practical applications of OOP in Python

- Hands-on projects and training geared towards job readiness

Why choose Uncodemy?

- You’ll earn an industry-recognized certification.

- Learn from expert mentors who bring real-world experience to the table.

- Get involved in live projects and benefit from placement support.

- Participate in resume and interview preparation sessions.

Embark on your Python programming journey with confidence and get job-ready with Uncodemy!

Conclusion

Polymorphism in Python empowers developers to create code that’s more abstract, flexible, and easier to maintain. Whether it’s through method overriding, default arguments, or the concept of duck typing, Python’s dynamic nature makes polymorphism not just intuitive but also incredibly powerful.

By grasping and utilizing polymorphism in Python, you’ll be well-prepared to design robust systems and write clean, extensible code. If you’re eager to boost your Python skills and get ready for the industry, think about enrolling in the Python Programming Course in Noida (uncodemy.com) to open up new doors in the tech world.

FAQs on Polymorphism in Python

Q1. Is Python statically typed or dynamically typed?

Ans. Python is dynamically typed, meaning that variable types are determined at runtime. This flexibility enables polymorphism through duck typing and adaptable method behavior.

Q2. Can you overload functions in Python?

Ans. While traditional function overloading (having the same name with different parameters) isn’t directly supported in Python, you can mimic it using default arguments or *args and **kwargs.

Q3. What is duck typing in Python?

Ans. Duck typing is a principle where the type of an object is less significant than the methods it possesses. If an object "quacks like a duck," it’s treated as a duck. This concept greatly facilitates polymorphism.

Q4. What’s the difference between overloading and overriding?

Overloading refers to having the same method name but with different parameters (this happens at compile-time).

Overriding involves redefining a method from a parent class in a child class (this occurs at run-time).

Q5. How does polymorphism benefit real projects?

Ans. Polymorphism allows a single interface to work with various data types or classes. This capability helps reduce code duplication, enhances reusability, and makes the code more extensible and scalable.

Q6. Can polymorphism be achieved without inheritance in Python?

Ans. Absolutely! Through duck typing and interfaces, Python enables polymorphism even without inheritance. If different objects implement the same method, they can be passed to the same function.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses