我在python3中读到了关于slice的文章。然后我编写了一个程序,试图实现__getitem__(self, slice(s))
。代码如下:
class NewList:
def __init__(self, lst):
print('new list')
self._list = lst
def __getitem__(self, x):
if type(x) is slice:
return [ self._list[n] for n in range(x.start, x.stop, x.step) ] #error?
else:
return self._list[x]
...
nl1 = NewList([1,2,3,4,5])
nl1[1:3] #error occurs
然后我发现x.step
是{__getitem__
方法呢?在
在不知道对象长度的情况下,有一个明显的技巧可以绕过这个强制参数。例如,无限序列的getitem可以如下所示:
它只会失败,如果你不给启动和停止,但没有检查,这也可以处理。在
如果
x
是一个切片,则可以执行与其他条件相同的操作:您需要使用
slice.indices
方法。给定序列的长度,它将返回start、stop、step的元组:相关问题 更多 >
编程相关推荐