+ 1

How do the magic-methods work?

class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y) My question is: how does the "second" variable get automatically placed as "other"? Since it's self.x + other.x, self.y + other.y, you just give two variables and they are automatically assigned without any extra details. How?

21st Aug 2020, 5:43 AM
Ville Nordström
Ville Nordström - avatar
1 Antwort
+ 1
The addition (the symbol +) is a binary operator, in the sense that it takes two arguments, the left and right sides of the + sign, in this line: result = first + second The left side is the object itself, in which the __add__ magic method is written. And the right side can be another object of the same type, or even some other type too. For example in Python we can legally multiply a string with a number. It is up to the implementation of these magic methods, what is considered to be a valid operation. To make the code more safe, we could check inside the __add__ method if the 'other' object is truly a Vector2D, and possibly raise an error if it isn't. But due to the dynamic nature of Python we can pass any object as the second argument, as long as it has an X and y property, the addition can still be successful.
30th Dec 2022, 5:10 PM
Tibor Santa
Tibor Santa - avatar