Python切片对象和__getitem__

wil*_*ill 5 python slice

python中是否有内部处理传递给__getitem_ _自变量的参数,并自动将start:stop:step构造转换为切片的工具?

这是我的意思的示范

class ExampleClass(object):

  def __getitem__(self, *args):
    return args

  def __call__(self, *args):
    return args

  def randomMethod(self, *args):
    return args


a = ExampleClass()

#this works
print a[3:7:2, 1:11:2]

#syntax error on the first colon
print a.randomMethod(3:7:2, 1:11:2)
print a(3:7:2, 1:11:2)

#these work
print a.randomMethod(slice(3,7,2), slice(1,11,2))
print a(slice(3,7,2), slice(1,11,2))
Run Code Online (Sandbox Code Playgroud)

难道仅仅是为实例解释搜索start:stop:step里面[]掉出来,并为slice(start, stop, step)?该文档只是说:

方括号(下标)表示法在内部使用切片对象

这是我无法更改其行为的python内部位之一吗?是否有可能使其他函数使用start:stop:step速记的切片对象?*

*我看到了另一个问题,可以在方括号之外使用python的切片符号吗?,但这只是使用自定义类完成的,我可以轻松做到。我想要的是一种start:stop:step无需包装即可使用的方法。

边注:

这也表明内部的所有参数[...]都打包到a中tuple,就好像它在执行[*args]->一样__getitem__(args)

class ExampleClass2(object):

  def __getitem__(self, arg):
    return arg

  def __call__(self, arg):
    return arg


b = ExampleClass2()

print b["argument 1", 2:4:6,3] # ('argument 1', slice(2, 4, 6), 3)
print b(slice(3,7,2), slice(1,11,2)) # TypeError: __call__() takes exactly 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)

Dun*_*can 5

Python语法定义何时可以使用slice运算符:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
Run Code Online (Sandbox Code Playgroud)

test几乎是任何表达式,但只有在subscriptlist其中可以使用slice运算符。所以是的,用于下标的方括号很重要,但是用于列表的方括号不可思议地允许您编写切片,也不能将切片放在恰好位于下标内部的任意表达式中。

如果在不下标的时候要切片,就必须写slice(a,b,c)