- Introduction to Polymorphism
- Types: Compile-Time vs Run-Time
- Method Overriding
- Duck Typing in Python
- Polymorphism with Inheritance
- Polymorphism with Functions and Objects
- Real-World Examples
- Conclusion
Introduction to Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. The word “polymorphism” means “many forms,” and in programming, it refers to the ability of different classes to respond to the same method call in different ways. In Python, polymorphism is typically achieved through method overriding and duck typing. Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. Duck typing, a dynamic feature of Python, allows an object’s behavior to determine its compatibility, rather than its class type “if it walks like a duck and quacks like a duck, it’s a duck.” For example, consider two different classes, Dog and Cat, both having a method called speak(). Even though they are different types of objects, they can be used interchangeably in a function that calls speak(), as long as both implement that method. Polymorphism promotes flexibility and scalability in code by enabling functions to operate on objects of different types without modification. This helps in writing more general and reusable code, which is one of the key principles of clean software design
Interested in Obtaining Your Python Certificate? View The Python Developer Course Offered By ACTE Right Now!
Types: Compile-Time vs Run-Time Polymorphism
Polymorphism is primarily categorized into two types:
- Compile-Time Polymorphism: Also known as static polymorphism or method overloading, it allows multiple methods in the same scope to have the same name but different signatures (number or type of parameters). Though widely supported in languages like Java and C++, Python does not support traditional method overloading in this sense. The latest defined method with the same name overrides any previously defined versions, thus Python leans away from compile-time polymorphism.
- Run-Time Polymorphism: Also known as dynamic polymorphism or method overriding, it occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method that gets executed is determined during runtime, based on the actual object type. This is fully supported in Python and forms the basis of polymorphic behavior in the language.
Method Overriding
In Python, run-time polymorphism is primarily achieved through method overriding. When a subclass defines a method with the same name as in the parent class, the subclass method overrides the superclass version. This allows for dynamic behavior changes without altering the interface.
- class Animal:
- def speak(self):
- print(“The animal makes a sound”)
- class Dog(Animal):
- def speak(self):
- print(“The dog barks”)
- class Cat(Animal):
- def speak(self):
- print(“The cat meows”)
- def make_sound(animal):
- animal.speak()
- make_sound(Dog())
- make_sound(Cat())
The make_sound() function demonstrates polymorphism, accepting any Animal subclass and executing the appropriate method.
Gain Your Master’s Certification in Python Developer by Enrolling in Our Python Master Program Training Course Now!
Duck Typing in Python
Python uses duck typing, a concept where the type or class of an object is less important than the methods it defines. The term “duck typing” comes from the phrase, “If it looks like a duck and quacks like a duck, it must be a duck.” This is a flexible form of polymorphism where object behavior is more critical than object inheritance.
- def fly(bird):
- bird.fly()
- class Sparrow:
- def fly(self):
- print(“Sparrow flying”)
- class Airplane:
- def fly(self):
- print(“Airplane flying”)
- fly(Sparrow())
- fly(Airplane())
In this example, both Sparrow and Airplane have a fly() method, and Python does not care about their class hierarchy, only about the presence of the required method.
Polymorphism with Inheritance
Polymorphism becomes even more powerful when combined with inheritance. In Python, a base class defines a general behavior and derived classes override or extend this behavior. This allows for creating highly reusable code with varying implementations.
- class Shape:
- def area(self):
- raise NotImplementedError(“Subclasses must implement this method”)
- class Rectangle(Shape):
- def __init__(self, width, height):
- self.width = width
- self.height = height
- def area(self):
- return self.width * self.height
- class Circle(Shape):
- def __init__(self, radius):
- self.radius = radius
- def area(self):
- return 3.14 * self.radius * self.radius
- shapes = [Rectangle(4, 5), Circle(7)]
- for shape in shapes:
- print(shape.area())
Each subclass of Shape provides its own version of the area() method, and Python executes the correct method based on the object type.
Are You Preparing for Python Jobs? Check Out ACTE’s Python Interview Questions and Answers to Boost Your Preparation!
Polymorphism with Functions and Objects
Python functions can operate on objects of different types, provided they share the required interface. This is useful for writing generic functions that are not tightly bound to specific classes.
- def describe(obj):
- print(obj.describe())
- class Book:
- def describe(self):
- return “This is a book”
- class Laptop:
- def describe(self):
- return “This is a laptop”
- describe(Book())
- describe(Laptop())
This level of flexibility improves the reusability and adaptability of the code.
Real-World Examples
Polymorphism is widely used in real-world applications:
- Web Frameworks: Django views often use polymorphism to handle different HTTP request methods (GET, POST).
- Machine Learning Libraries: Scikit-learn’s fit() and predict() methods behave polymorphically across different model classes.
- Database Access: ORMs like SQLAlchemy use polymorphism to map different database models using a common interface.
- Graphics Engines: Games and UI libraries render different objects (characters, icons) using a shared render() method.
Conclusion
Polymorphism in Python is a powerful feature that enables writing flexible, modular, and extensible code. It supports both method overriding and dynamic typing (duck typing), allowing functions and classes to operate on objects of different types with shared interfaces. Whether used in simple scripts or complex enterprise applications, polymorphism enhances code maintainability and reusability. With features like abstract base classes, inheritance, dynamic polymorphism and dynamic function dispatch, Python equips developers with all the necessary tools to implement polymorphic behavior effectively. Understanding and applying polymorphism is crucial for mastering object-oriented programming in Python and designing scalable software systems.