简体   繁体   English

Python - 基本与扩展切片

[英]Python - Basic vs extended slicing

When experimenting with slicing I noticed a strange behavior in 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))

When using a single colon in the brackets, the slice object has 0 as start and a huge integer as end. 在括号中使用单个冒号时,切片对象的开头为0,结尾为大整数。 However, when I use more than a single colon, start and stop are None if not specified. 但是,当我使用多个冒号时,如果未指定,则start和stop为None。

Is this behaviour guaranteed or implementation specific? 这种行为是保证还是实现特定的?

The Documentation says that the second and third case are extended slicing, while the first case is not. 文档说第二和第三种情况是扩展切片,而第一种情况则不是。 However, I couldn't find any clear explanation of the difference between basic and extended slicing. 但是,我找不到基本切片和扩展切片之间差异的任何明确解释。

Are there any other "special cases" which I should be aware of when I override __getitem__ and want to accept extended slicing?? 当我覆盖__getitem__并希望接受扩展切片时,我是否应该注意其他“特殊情况”?

For Python 2 [:] still calls __getslice__(self, i, j) (deprecated) and this is documented to return a slice slice(0, sys.maxsize, None) when called with default parameters: 对于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 , ... 请注意,切片表达式中缺少ij将替换为零sys.maxsize ,...

(emphasis mine). (强调我的)。 New style classes don't implement __getslice__() by default, so 默认情况下,新样式类不实现__getslice__()

If no __getslice__() is found, a slice object is created instead, and passed to __getitem__() instead. 如果未__getslice__() ,则会创建切片对象,并将其传递给__getitem__()

Python 3 doesn't support __getslice__() , anymore, instead it constructs a slice() object for all of the above slice expressions. Python 3不再支持__getslice__() ,而是为所有上述切片表达式构造一个slice()对象。 And slice() has None as default: 并且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 . 缺少切片项目始终使用“ None填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM