问题描述
我有一个将列表对象子类化的类.现在,我需要处理切片.从我在管间读取的所有内容来看,都必须使用__getitem__
方法来完成.至少在我使用的Python 2.7+中.我已经做到了(见下文),但是当我传递切片时,不会调用__getitem__
方法.相反,将完成切片并返回列表.我想要一个myList的新实例返回.
I have a class that subclasses the list object. Now I need to handle slicing. From everything I read on the intertubes this has to be done using the __getitem__
method. At least in Python 2.7+ which is what I'm using. I have done this (see below), but the __getitem__
method isn't called when I pass in a slice. Instead, a slice is done and a list is returned. I would like a new instance of myList returned.
请帮助我发现问题所在.
Please help me discover what is wrong.
谢谢!
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]
推荐答案
请参见:
自版本2.0起不推荐使用:支持 将对象切片为参数 __getitem__()
方法. (但是,当前CPython中的内置类型 仍实施__getslice__()
. 因此,您必须在 实现时的派生类 切片.
Deprecated since version 2.0: Support slice objects as parameters to the __getitem__()
method. (However, built-in types in CPython currently still implement __getslice__()
. Therefore, you have to override it in derived classes when implementing slicing.
因此,因为您继承了list
的子类,所以即使不推荐使用它也必须覆盖__getslice__
.
So, because you subclass list
you have to overwrite __getslice__
, even though it's deprecated.
我认为您通常应该避免对内建函数进行子类化,因为有太多奇怪的细节.如果您只想要一个行为类似于列表的类,则可以使用 ABC 可以帮助您解决此问题:
I think you should generally avoid subclassing builtins, there are too many weird details. If you just want a class that behaves like a list, there is a ABC to help with that:
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)
这篇关于自定义Python切片,请告知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!