如何对<class'int> + <class'Vector'>求和

时间:2019-09-10 21:18:47

标签: python-3.x oop magic-methods

我对sum和有一些问题 这样:1 +(x,y)=(1 + x,1 + y),但这是行不通的。如果我尝试逆向求和,并且与(x,y)+ 1 =(x + 1,y + 1),这将正常工作。

更改此:

return (self.x + other, self.y + other) 

对此:

return (other + self.x, other + self.y)

不起作用

class Vector():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'({self.x}, {self.y})'

    def __add__(self, other):
        if isinstance(other, Vector):
            return (self.x + other.x, self.y + other.y)
        else:
            return (self.x + other, self.y + other) 

x = Vector(1, 4)
y = Vector(10, 10)
print(x + y) #  (11, 14)
print(x + 2) #  (3, 6)
print(2 + x) #  TypeError: unsupported operand type(s) for +: 'int' and 'Vector'

0 个答案:

没有答案