Python切片对象和__getitem__ [英] Python slice objects and __getitem__

查看:41
本文介绍了Python切片对象和__getitem__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)?文档简单地写着:

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

这是不能更改其行为的Python内部位之一吗?是否可以让其他函数使用start:stop:step速记?*

*我已经看到了另一个问题,Can python's 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)

Python

推荐答案语法定义何时可以使用切片运算符:

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

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

如果您在不订阅某些内容时想要切片,则必须编写slice(a,b,c)

这篇关于Python切片对象和__getitem__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆