Polymorphism Python
Python tutorial · PySpark.in
What is Polymorphism?
Polymorphism means “many forms.” In Python OOP, it allows the same function or method name to behave differently based on the object or data type it is acting upon.
Real-Life Example
Think about the word “run”:
- A person can run
- A car can run
- A program can run
Even though the action “run” is the same word, it behaves differently based on who or what is performing it. That’s Polymorphism.
Example 1: Built-in Polymorphism
Python supports polymorphism even with built-in functions.
The same len() function works differently for strings, lists, and dictionaries.
Example 2: Polymorphism with Classes and Methods
polymorphism works with user-defined classes.
A subclass can override a method from its parent class.
Here, the same method flight() behaves differently for different objects (Bird and Penguin).
Example 3: Polymorphism Using a Common Interface
Different objects can be passed to the same function, and the function will call their respective methods.
Same function animal_sound()
Works for both Dog and Cat
That’s polymorphism through duck typing
Example 4: Polymorphism with Inheritance and super()
Both Circle and Rectangle override the same method area() — this is method overriding, a type of polymorphism.
Both classes provide their own version of area()
This is method overriding → a key form of polymorphism
Why Polymorphism Is Important?
-
Makes code flexible
-
Allows writing common interfaces
-
Supports method overriding
-
Key to writing clean OOP-based applications
-
Helps implement inheritance, interfaces, and abstract classes
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges