如何在python中重写list方法来进行向量加减呢?

2024-05-20 18:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我最初是将它作为一个围绕列表的包装类来实现的,但是我对需要提供的操作符()方法的数量感到恼火,所以我尝试简单地将list子类化。这是我的测试代码:

    class CleverList(list):

        def __add__(self, other):
            copy = self[:]
            for i in range(len(self)):
                copy[i] += other[i]
            return copy

        def __sub__(self, other):
            copy = self[:]
            for i in range(len(self)):
                copy[i] -= other[i]
            return copy

        def __iadd__(self, other):
            for i in range(len(self)):
                self[i] += other[i]
            return self

        def __isub__(self, other):
            for i in range(len(self)):
                self[i] -= other[i]
             return self

    a = CleverList([0, 1])
    b = CleverList([3, 4])
    print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b)

    c = a[:]
    print('clone test: e = a[:]: a, e = ', a, c)

    c += a
    print('OOPS: augmented addition: c += a: a, c = ', a, c)

    c -= b         
    print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a)

正常的加减法按预期的方式工作,但增广加减法存在问题。输出如下:

^{pr2}$

在这个例子中,有没有一种简单明了的方法让增广运算符工作?在


Tags: 方法inselfforlenreturndefrange