0

How did they get this result even though there is a subtraction. P1-P2

class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __sub__(self, other): x = self.x + other.x y = self.y + other.y return Point(x,y) p1 = Point(3, 4) p2 = Point(1, 2) result = p1-p2 print(result.x, result.y) result : 4 6

11th Mar 2019, 6:06 PM
Smail Benloukil
Smail Benloukil - avatar
2 odpowiedzi
+ 3
Because you redefined subtraction as addition in sub function, literally you said to - to act as +
11th Mar 2019, 6:14 PM
Elva
Elva - avatar
+ 2
This is called 'operator overload': You define what a certain operator is supposed to do with that type. For example when you add two numbers like 5+5, the result is 10 as you'd expect, but if you write '5' + '5', the result is '55' - because + has been given another meaning. And __sub__ defines what happens when you use - on that type. (And it can even be nonsense, like in this case.)
11th Mar 2019, 7:13 PM
HonFu
HonFu - avatar