Polymorphism
Learn how to implement polymorphism in Python to use a single interface for different data types and allow methods to behave differently based on the object type.
Concept
The ability to use a single interface to represent different underlying data types. It allows methods to do different things based on the object it is acting upon. Also, it allows methods to have the same name but behave differently based on the object type by using method overriding or method overloading.
Types of Polymorphism | Description |
---|---|
Compile-time Polymorphism (Method or operator overloading) | The method to be executed is determined at compile time. It allows the same method name to be used with different parameters or types. |
Runtime Polymorphism (Method Overriding) | The method to be executed is determined at runtime. It allows a subclass to provide a specific implementation of a method that is already defined in its superclass. |
Implementation
Method Overriding
Based on the below example, the area
method is overridden in the Circle
and Rectangle
classes to provide specific implementations for calculating the area of each shape. The Shape
class serves as a base class with a generic area
method.
Method Overloading
Based on the below example, the add
method is overloaded to handle different numbers of parameters. The method can accept either two or three arguments, and it will return the sum accordingly.
Operator Overloading
More Information
Methods like __add__
, __str__
, __eq__
, etc are called dunder methods (double underscore methods) or magic methods. They allow you to define how operators and built-in functions behave for user-defined classes.
Operator overloading allows you to define how operators behave for user-defined classes. For example, you can define how the +
operator works for a custom class by implementing the __add__
method.