27. Python Polymorphism
Python Polymorphism
The word polymorphism means "many forms", and in programming it refers to methods, functions, or operators with the same name that can be executed on many objects or classes.
It allows us to define methods in the child class that have the same name as the methods in the parent class, or to use a single function to process different types of data seamlessly.
Function Polymorphism
An excellent example of built-in Python polymorphism is the len() function. You can use it on completely different data types, and it inherently knows how to handle each one.
Even though the objects are completely different, the len() function seamlessly adapts its behavior to fit the object.
Class Polymorphism
Polymorphism is highly prevalent in Class methods. We can have multiple completely different classes that share the exact same method names.
Notice the loop. Because of polymorphism, we can execute the exact same method move() on all three objects, even though they are completely different classes.
Inheritance Class Polymorphism
Polymorphism works perfectly alongside Inheritance. If we create a base parent class, we can have child classes that inherit its methods, but override them to provide specific, polymorphic behavior.
In this architecture, the Car class is empty, so it falls back to inheriting the default move() method from the Vehicle parent class. The Boat and Plane classes are polymorphic — they override the method to provide their own distinct implementation.
Knowledge Check
Ready to test your understanding of 27. Python Polymorphism?