在尝试切片时,我注意到 Python 2.7 中的一个奇怪行为:
class A:
def __getitem__(self, i):
print repr(i)
a=A()
a[:] #Prints slice(0, 9223372036854775807, None)
a[::] #prints slice(None, None, None)
a[:,:] #prints (slice(None, None, None), slice(None, None, None))
当在括号中使用单个冒号时,切片对象以 0 作为起点,以一个巨大的整数作为终点。但是,当我使用多个冒号时,如果未指定,开始和停止都是 None。
这种行为是有保证的还是特定于实现的?
Documentation表示第二种和第三种情况是扩展切片,而第一种情况不是。但是,我找不到任何关于基本切片和扩展切片之间区别的明确解释。
当我重写 __getitem__
并想要接受扩展切片时,是否还有其他我应该注意的“特殊情况”??
最佳答案
对于 Python 2 [:]
仍然调用 __getslice__(self, i, j)
(已弃用)并且记录在使用默认参数调用时返回切片 slice(0, sys.maxsize, None)
:
Note that missing
i
orj
in the slice expression are replaced by zero orsys.maxsize
, ...
(强调我的)。
默认情况下,新样式类不实现 __getslice__()
,因此
If no
__getslice__()
is found, a slice object is created instead, and passed to__getitem__()
instead.
Python 3 不再支持 __getslice__()
,取而代之的是 constructs a slice()
上述所有切片表达式的对象。 slice()
默认有 None
:
Note: Slicing is done exclusively with the following three methods. A call like
a[1:2] = b
is translated to
a[slice(1, 2, None)] = b
and so forth. Missing slice items are always filled in with
None
.
关于Python - 基本切片与扩展切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037663/