+ 1
I have been trying to understand this for the past 5 days. But couldn't.. i mean i never get even one percent of pythons
dunders and operator overloading... a little help could be appreciated and thankful. 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)
3 Réponses
+ 3
The code created a class whose name is "Vector2D" that contains 2 variables x and y and a method for addition that adds x's together and y's together then the code created 2 variables which are named "first" and "second" and assigned different values to each of them then added them using the addition method that is explained before
I wish that could help you
0
When you do "a+b", what really happens is that Python itself tries to call "a.__add__(b)". If there is that method, great, use that answer. If there isn't, it then tries to call "b.__radd__(a)". If there is not, it throws an error (I don't remember which one, might be a TypeError, but I'm not sure).