Python片对象和getitem方法

2024-06-26 02:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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)。在

^{pr2}$

Tags: self参数returndefstepargsslicestart
2条回答

Python语法定义了何时可以使用slice操作符:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]

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

如果你在没有订阅的时候想要切片,你必须写slice(a,b,c)。在

np.lib.index_tricks包含几个接受::输入的“函数”,例如np.mgridnp.r_np.s_。在

它们实际上是用__getitem__定义实现的类实例。它们用方括号“称为”。在

np.s_[2::2] #  slice(2, None, 2)
np.r_[-1:1:6j, [0]*3, 5, 6]  # array([-1. , -0.6, -0.2,  0.2, ... 6. ])
mgrid[0:5,0:5]

我通常不使用它们,但它们是如何利用__getitem__的一个有趣的例子。在

np.insert是生成包含切片的索引元组的函数的示例。np.apply_along另外:

^{pr2}$

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html 有相关说明:

Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects can be used in the construction in place of the [start:stop:step] notation. For example, x[1:10:5,::-1] can also be implemented as obj = (slice(1,10,5), slice(None,None,-1)); x[obj] . This can be useful for constructing generic code that works on arrays of arbitrary dimension.

相关问题 更多 >