0

Can anyone answer me this question in Python? Thx

Why the first one no need “Vector2D” in return but the second need ? Thanks class Vector2D: def __init__(self, x): self.x = x def __truediv__(self, other): return self.x + other.x first = Vector2D(5) second = Vector2D(3) print(first/second) 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)

4th Oct 2021, 3:10 PM
Jeffrey Wu
2 Réponses
+ 2
Because the first returns only a number. 5 + 3 - > 8 But the second one returns a new object of Vector2D. So result becomes an object of Vector2D, not only a "simple" number.
4th Oct 2021, 3:29 PM
Coding Cat
Coding Cat - avatar
+ 1
I don't know why you are adding member <x> from two objects <self> and <others> in the __truediv__ magic method. It's supposed to return a floating point division result. You can return a Vector2D object from the __truediv__ magic if you choose so though ...
4th Oct 2021, 3:45 PM
Ipang