Python slice objects and __getitem__(Python切片对象和__getitem__)
本文介绍了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__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Python切片对象和__getitem__


基础教程推荐
猜你喜欢
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01