您需要提供定制__getitem__() http://docs.python.org/reference/datamodel.html#object.__getitem__, __setitem__ http://docs.python.org/reference/datamodel.html#object.__setitem__ and __delitem__ http://docs.python.org/2/reference/datamodel.html#object.__delitem__ hooks.
这些都通过了切片对象 http://docs.python.org/library/functions.html#slice对列表进行切片时;这些有start
, stop
and step
属性。然而,这些值可能是None
,表示默认值。请注意,当您使用负步幅时,默认值实际上会发生变化!
然而,他们也有一个slice.indices() method https://docs.python.org/reference/datamodel.html#slice.indices,当给定长度时会产生一个元组(start, stop, step)
值适合于range()
目的。此方法处理诸如以负步长进行切片且没有开始或停止索引等烦人的细节:
def __getitem__(self, key):
if isinstance(key, slice):
indices = range(*key.indices(len(self.list)))
return [self.list[i] for i in indices]
return self.list[key]
或者,对于您的情况:
def __getitem__(self, key):
return self.list[key]
因为一个list
可以采取slice
直接反对。
在Python 2中,list.__getslice__ https://docs.python.org/2/reference/datamodel.html#object.__getslice__如果实现的话,会为没有跨度的切片调用(因此只有开始和停止索引),并且内置list
type 实现了它,所以你也必须重写它;一个简单的代表团给您__getitem__
方法应该做得很好:
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))