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

Course Content

In-Depth Python OOP

In-Depth Python OOP

1. OOP Concepts
2. Inheritance
3. Encapsulation
4. Polymorphism and Abstraction
5. Magic Methods

bookMath 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:

1234
a, b = 25, 12 print("a * b =", a * b) print("a.__mul__(b) =", a.__mul__(b))
copy

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:

1234567891011121314151617
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)
copy

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?

Which magic method should be used?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt