11.4 Overloading operators
Learning objectives
By the end of this section you should be able to
- Identify magic methods and describe their purpose.
- Develop overloaded arithmetic and comparison operators for user-defined classes.
Magic methods and customizing
Magic methods are special methods that perform actions for users, typically out of view of users. Magic methods are also called dunder methods, since the methods must start and end with double underscores (__). Ex: __init__ is a magic method used alongside __new__ to create a new instance and initialize attributes with a simple line like eng = Engineer. A programmer can explicitly define a magic method in a user-defined class to customize the method's behavior.
Overloading arithmetic operators
Operator overloading refers to customizing the function of a built-in operator. Arithmetic operators are commonly overloaded to allow for easy changes to instances of user-defined classes.
| Arithmetic operator (Operation) | Magic method |
|---|---|
| + (Addition) | __add__(self, other) |
| - (Subtraction) | __sub__(self, other) |
| * (Multiplication) | __mul__(self, other) |
| / (Division) | __truediv__(self, other) |
| % (Modulo) | __mod__(self, other) |
| ** (Power) | __pow__(self, other) |
Overloading comparison operators
Comparison operators can also be overloaded like arithmetic operators.
| Comparison operator (Operation) | Magic method |
|---|---|
| < (Less than) | __lt__(self, other) |
| > (Greater than) | __gt__(self, other) |
| <= (Less than or equal to) | __le__(self, other) |
| >= (Greater than or equal to) | __ge__(self, other) |
| == (Equal) | __eq__(self, other) |
| != (Not equal) | __ne__(self, other) |