0
Why this code of method overloading not working? The only addition I made was one more to original one as described in dunders
class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other, onemore): return Vector2D(self.x + other.x + onemore.x, self.y + other.y + onemore.y) first = Vector2D(5, 7) second = Vector2D(3, 9) third = Vector2D(2, 4) result = first + second + third print(result.x) print(result.y)
2 odpowiedzi
+ 3
This code will give you a type error.
when you write:
a + b + c
python implicitly calls:
a.__add__(b.__add__(c))
so the third parameter (one more) never gets passed to your overloaded __add__ method.
the reason for this is + is a binary operator, Bi meaning 2. it only works on two operands. therefore it only takes two parameters: self and other
to make your code work you'd have to do:
a.__add__(b, c) which defeats the purpose of the + operator
0
thanx a lot that's why I have seen loads of examples on net where there are self and other ie. 2 args and not 3