0
Can somone explaine this code for me?
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)
1 Answer
+ 2
For every type, it can be defined what happens if you use operators on them.
If you write 1+1, you'll get 2.
If you write '1'+'1', you'll get '11'.
If you write [1]+[1], you'll get [1, 1].
So int, str and list all have their own way of adding.
This self-defined type Vector2d says that when you __add__ two vectors (use + on them), you'll get a new vector with the x and y attributes of each vector added.
Try to read the code again with the explanation and see if it makes more sense now.