0
i dont understand how the add function is picking x of other cause i thinking it should be picking another arrtibute of first on
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) //output-8 16
2 Antworten
+ 2
When you do....
result = first + second
...what your actually doing is...
result = first.__add__(second)...the "second" is the "other" in the magic method.
+ 1
+ is defined as doing what's defined in __add__, returning a new Vector with the x values and the y values added.
In this program, first will be self, second will be other.
5+3 == 8
7+9 == 16
Is it getting clearer like this?