Concept
Polymorphism is the ability to use a single interface to represent different underlying data types. It allows methods to do different things based on the object they are acting upon — methods can have the same name but behave differently based on the object type.| Type | Description |
|---|---|
| Compile-time Polymorphism (Method/Operator Overloading) | The method to be executed is determined at compile time. 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. Allows a subclass to provide a specific implementation of a method already defined in its superclass. |
Implementation
Method Overriding
Thearea method is overridden in Circle and Rectangle to provide shape-specific implementations. The Shape class serves as a base class with a generic area method.
shapes.py
Method Overloading
Python does not natively support method overloading (the last definition wins), but you can simulate it using default arguments or*args.
calculator.py
Operator Overloading
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.+, ==) work for custom classes by implementing the corresponding dunder method.
vector.py
| Dunder Method | Operator | Description |
|---|---|---|
__add__ | + | Addition |
__sub__ | - | Subtraction |
__mul__ | * | Multiplication |
__eq__ | == | Equality check |
__str__ | str() | String representation |
__len__ | len() | Length |