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))
只是解释器在[]中搜索start:stop:step的实例,并将它们换成切片(开始,停止,步骤)?文档简单地说:
The bracket (subscript) notation uses slice objects internally
这是我不能改变行为的python内部位之一吗?是否有可能使其他函数采用切片对象使用start:stop:step速记?*
*我已经看到了另一个问题,Can python’s slice notation be used outside of brackets?,但这只是使用自定义类,我可以轻松做到.我想要的是一种只使用start:stop:step的方法,而不必将其包装在其他任何东西中.
边注:
它也表明[…]内的所有参数都被打包成一个元组,就好像它正在做[* args] – > __getitem __(参数).
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)
解决方法:
Python语法定义何时可以使用切片运算符:
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
test几乎是任何表达式,但它只能在子脚本列表中使用切片运算符.所以是的,用于下标的方括号是重要的,但是用于列表的方括号不会神奇地允许你写一个切片,也不能将切片放在恰好位于下标内的任意表达式中.
如果你想要切片,当你没有订阅东西时,你必须写切片(a,b,c).
标签:python,slice