0
Can any one explain the "other" keyword and the functionality of the code
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
+ 5
'other' is like 'self' - it's just a convention to use such a variable name, it can be anything.
In this particular case it is referring to the second argument of the __add__ method (which always takes two arguments), as you add one thing to the other.
As for functionality - it's a code implementing class and defining the addition operation for it. If you then use it on two objects of this class (and add them up) the result you get back is another object of the same class with its x and parameters being sums of respective xs and ys of the two added ones.