Python - 基本切片与扩展切片

标签 python python-2.7

在尝试切片时,我注意到 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 or j in the slice expression are replaced by zero or sys.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/

相关文章:

python - 在 Python 中查找系统文件夹位置

python - 在python中递归退出矩形

python - 使用 SymPy 求解方程的 2 条边

python - 如何将字符串仅附加到列表中的辅音?

python - 如何存储决策树

python - Google App Engine 本地开发服务器不路由到远程云存储桶

python - 如何以编程方式使用其他 python 版本运行另一个 python 脚本?

python - 使用bash运行python脚本

python - 为什么Python的max()函数不准确?

python-2.7 - 使用 Python API 在优化失败后获取 NLOpt 结果