如何覆盖列表方法在python中进行向量加法和减法?

时间:2012-06-30 15:11:28

标签: python list operators subclass

我最初将它实现为一个列表的包装类,但我对我需要提供的运算符()方法的数量感到恼火,所以我只是简单地继承了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)

正常的加法和减法以预期的方式工作,但增强加法和减法存在问题。这是输出:

    >>> 
    CleverList does vector arith: a, b, a+b, a-b =  [0, 1] [3, 4] [3, 5] [-3, -3]
    clone test: e = a[:]: a, e =  [0, 1] [0, 1]
    OOPS: augmented addition: c += a: a, c =  [0, 1] [0, 1, 0, 1]
    Traceback (most recent call last):
      File "/home/bob/Documents/Python/listTest.py", line 35, in <module>
        c -= b
    TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList'
    >>> 

是否有一种简洁的方法可以让增强运算符在这个例子中工作?

1 个答案:

答案 0 :(得分:5)

您未覆盖__getslice__ method,因此clist

>>> a = CleverList([0, 1])
>>> a
[0, 1]
>>> type(a)
<class '__main__.CleverList'>
>>> type(a[:])
<type 'list'>

这是一个袖手旁观的版本:

def __getslice__(self, *args, **kw):
    return self.__class__(super(CleverList, self).__getslice__(*args, **kw))