自定义Python切片,请指教

jlc*_*lin 7 python list slice

我有一个子类列表对象的类.现在我需要处理切片.从我在intertubes上读到的所有内容中,必须使用该__getitem__方法完成.至少在我正在使用的Python 2.7+中.我已经完成了这个(见下文),但是__getitem__当我传入切片时没有调用该方法.而是完成切片并返回列表.我想返回一个新的myList实例.

请帮我发现错误.

谢谢!

class myList(list):

    def __init__(self, items):

        super(myList, self).__init__(items)
        self.name = 'myList'


    def __getitem__(self, index):

        print("__getitem__")
        if isinstance(index, slice):
            print("slice")
            return self.__class__(
                self[x] for x in range(*index.indices(len(self)))
                )
        else: return super(myList, self).__getitem__(index)

if __name__ == "__main__":
    print("\nI'm tesing out custom slicing.\n")

    N = 10
    L = myList(range(N))

    L3 = L[3]
    L02 = L[:2]
Run Code Online (Sandbox Code Playgroud)

Joc*_*zel 17

本说明:

object.__getslice__(self, i, j)

自2.0版开始不推荐使用:支持切片对象作为__getitem__()方法的参数 .(但是,CPython中的内置类型目前仍在实现__getslice__(). 因此,在实现切片时必须在派生类中重写它.

所以,因为你是子类,list你必须覆盖__getslice__,即使它已被弃用.

我认为你通常应该避免对内置类进行子类化,有太多奇怪的细节.如果你只是想要一个行为类似于列表的类,那么有一个ABC来帮助它:

from collections import Sequence

class MyList(Sequence):
    def __init__(self, *items):
        self.data = list(items)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, slice):
        return self.data[slice]

s = MyList(1,2,3)
# lots of free methods
print s[1:2], len(s), bool(s), s.count(3), s.index(2), iter(s)
Run Code Online (Sandbox Code Playgroud)