当python的`in`函数通过`__getitem __()`’触发时,它是如何工作
发布时间:2020-12-20 11:06:33 所属栏目:Python 来源:网络整理
导读:The official documentation表示python首先尝试通过__contains __(),然后__iter __(),最后__getitem __()进行检查,具体取决于定义的函数,以便解析调用. 例如: if y in x: print("y present in x")else: print("y not present in x") 链接的文档表明,如果存
The official documentation表示python首先尝试通过__contains __(),然后__iter __(),最后__getitem __()进行检查,具体取决于定义的函数,以便解析调用.
例如: if y in x: print("y present in x") else: print("y not present in x") 链接的文档表明,如果存在任何非负索引i,使得x [i] == y,则结果为True,否则为False. 解决方法
Aaah,我认为得到它…你想知道如何获取密钥来迭代自定义容器上的所有元素,这些容器既没有__contains __()也没有__iter __() – 简单,它完全使用线性迭代直到
IndexError 是遇到的,如文件中所述:
例证: class CustomClass(object): def __getitem__(self,item): if item > 20: # lets force the break so that it doesn't go to sys.maxsize raise IndexError() print(item) # print the item requested # implied: return None so it doesn't match 5 result = 5 in CustomClass() # this will keep printing numbers until 20 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |