Operator Overloading
- Operator overloading allows user-defined classes to redefine the behavior of operators like
+,-,*, etc. - This is done by defining special methods inside the class.
Example: Overloading + for Time class (from 17.7)
class Time:
def __add__(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
Usage:
start = Time(9, 45) duration = Time(1, 35) print(start + duration) # Output: 11:20:00
Python internally calls start.__add__(duration).
Five Common Operators and Their Special Methods
| Operator | Special Method | Usage Example |
|---|---|---|
+ | __add__(self, other) | a + b |
- | __sub__(self, other) | a - b |
* | __mul__(self, other) | a * b |
== | __eq__(self, other) | a == b |
< | __lt__(self, other) | a < b |
These methods can be defined in custom classes to perform operations based on object data instead of default behavior.
