Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
Math Magic Methods
There are additional magic methods for various math operations in Python. In addition to the __add__
magic method, which is used for addition, there are other magic methods for different mathematical operations:
Magic Method | Operation |
__add__(self, other) | + |
__sub__(self, other) | - |
__mul__(self, other) | * |
__pow__(self, other) | ** |
__mod__(self, other) | % |
__truediv__(self, other) | / |
__floordiv__(self, other) | // |
These magic methods typically receive two arguments: self
(representing the instance, which is the right operand in the expression) and other
(representing the left operand in the expression). By convention, it is common to refer to the second argument as other
or other_obj
, but you have the flexibility to use a different name if it makes the code more meaningful or clear in the context of your class and its operations. The name of the second argument should reflect its purpose and role in the mathematical operation being implemented.
Let's look at the example with int
object:
a, b = 25, 12 print("a * b =", a * b) print("a.__mul__(b) =", a.__mul__(b))
Creating a magic method in Python allows us to define custom logic for mathematical operators. Typically, these methods return a new instance of the class where certain attributes are added, multiplied, divided, etc. For example, in a Road
class, the +
operator could return a new road with the added length, as discussed in the first chapter of this section.
Let's improve the example from the first chapter of this section:
class Road: def __init__(self, length): self.length = length def __add__(self, other): if isinstance(other, Road): return Road(self.length + other.length) return Road(self.length + other) road_1 = Road(20) road_2 = Road(30) road_3 = road_1 + road_2 # road_3 = road_1.__add__(road_2) road_4 = road_2 + 62 print(type(road_3), type(road_4)) print(road_3.length) print(road_4.length)
Compared to Java or JavaScript, in Python, instead of defining a regular method add
to add classes, we can change the behavior of the +
operator, which is much more convenient to use (instance1 + instance2
) than calling instance1.add(instance2)
every time.
Дякуємо за ваш відгук!