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
的实例,并将它们交换为slice(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
而不必将其包装在其他任何东西中的方法。在
旁注:
它还表示[...]
中的所有参数都打包成tuple
,有点像它在做[*args]
->;__getitem__(args)
。在
Python语法定义了何时可以使用slice操作符:
test
几乎是任何表达式,但只有在subscriptlist
中才能使用slice运算符。所以,是的,用于下标时的方括号是重要的,但是用于列表的方括号不会神奇地允许您编写切片,也不能将切片放入恰好位于下标中的任意表达式中。在如果你在没有订阅的时候想要切片,你必须写
slice(a,b,c)
。在np.lib.index_tricks
包含几个接受::
输入的“函数”,例如np.mgrid
,np.r_
,np.s_
。在它们实际上是用
__getitem__
定义实现的类实例。它们用方括号“称为”。在我通常不使用它们,但它们是如何利用
__getitem__
的一个有趣的例子。在
^{pr2}$np.insert
是生成包含切片的索引元组的函数的示例。np.apply_along
另外:http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html 有相关说明:
相关问题 更多 >
编程相关推荐