Polymorphism
Polymorphism, one of the core concepts in object-oriented programming (OOP), provides the ability to take on many forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. It’s a feature that allows an object to exhibit different behaviors according to its state or the context in which it’s used.
Python Polymorphism with functions and objects
We can create a function that can take any object, allowing for polymorphism. Let’s look at a simple Python program to show how polymorphism works with functions and objects:
Polymorphism with inheritance
With inheritance, the child class inherits methods from the parent class. However, there are situations where the method inherited from the parent class doesn’t quite fit into the child class. In such cases, we re-implement the method in the child class. This process is known as Method Overriding. Overriding is, therefore, a part of the polymorphism feature.
With Method Overriding in place, we’re able to ensure that each subclass identifies a method in its own way, which is a key principle of polymorphism.
Note
The method of the child class will always be executed if the parent and child class both have a method with the same name.
Polymorphism not only makes for a cleaner, more intuitive design, but it also makes software more maintainable by making it more scalable and robust.