Python 已覆盖 __add__ 不适用于 a += b

Python Overridden __add__ Doesn't Work for a += b

我一直在研究 Vector 对象 class 以允许我使用 Python 快速解决数学问题。

例如: 如果我们设置 vector = Vector(1, 2, 3) 和 运行 vector *= 2,那么 vector 将等于 <2, 4, 6>

问题: 每当我 运行 vector += 2 时,它会出错说

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 149, in <module>
    main()
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 139, in main
    vector += 2
TypeError: 'int' object is not iterable

Process finished with exit code 1

这是我的向量class

class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

这是我的主要功能

def main():
    vector = Vector(1, 2, 3)
    vector *= 2
    print(vector)
    vector += 2
    print(vector)

我为找到解决方案所做的工作:

只需添加行 __iadd__ = __add__:

class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    __iadd__ = __add__

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"


vector = Vector(1, 2, 3)
vector *= 2
print(vector)
vector += 2
print(vector)

打印:

<2, 4, 6>
<class 'int'>
<4, 6, 8>