0

我最初将其实现为围绕列表的包装类,但我对需要提供的operator () 方法的数量感到恼火,因此我尝试简单地对列表进行子类化。这是我的测试代码:

    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'
    >>> 

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

4

1 回答 1

5

您没有覆盖该__getslice__方法,因此您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))
于 2012-06-30T15:19:35.577 回答