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
inside []
,并将它们交换为slice(start, stop, step)
?该文档简单地说:
括号(下标)表示法在内部使用切片对象
这是我无法改变其行为的 python 内部位之一吗?是否可以使其他函数使用切片对象start:stop:step
速记?*
*我看过另一个问题,python 切片表示法可以在括号之外使用吗? https://stackoverflow.com/questions/11980524/can-pythons-slice-notation-be-used-outside-of-brackets,但这只是使用自定义类来实现的,我可以轻松做到这一点。我想要的是一种只使用的方法start:stop:step
无需将其包裹在其他任何东西中。
边注:
看来里面的所有论点[...]
被打包成一个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)