楼上虽然说明了有些内容会转成 tuple,不过以前没见过这种写法,还是不清楚是怎么转成 tuple 的,就研究了下。
https://docs.python.org/3/reference/expressions.html#slicingsThe semantics for a slicing are as follows. The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.
对于表达式 a[`.+`] 如果 正则 `.+` 至少包含一个逗号,则 key 为一个 tuple,否则 key 为 slice。
下面的示例能更清楚地说明上面的规则:
$ cat
test.py && python3
test.pyclass A():
def __getitem__(self, *args, **kwargs):
print('args:', len(args), args[0])
a = A()
a[1:]
a[:2]
a[1:2]
a[1,:]
a[:,2]
a[1,:,2]
# end of
test.pyargs: 1 slice(1, None, None)
args: 1 slice(None, 2, None)
args: 1 slice(1, 2, None)
args: 1 (1, slice(None, None, None))
args: 1 (slice(None, None, None), 2)
args: 1 (1, slice(None, None, None), 2)