Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Math Magic Methods | Magic Methods
In-Depth Python OOP
course content

Зміст курсу

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 MethodOperation
__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:

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:

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.

Which magic method should be used?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 5. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt