加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

当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.
它如何对所有这样的i进行搜索?对“所有”正数进行线性遍历似乎是不可能的.必须有一些线性遍历发生的界限(对于列表,它应该是0到len()).这些界限是如何确定的?

解决方法

Aaah,我认为得到它…你想知道如何获取密钥来迭代自定义容器上的所有元素,这些容器既没有__contains __()也没有__iter __() – 简单,它完全使用线性迭代直到 IndexError是遇到的,如文件中所述:

… if a class defines __getitem__(),x in y is True if and only if there is a non-negative integer index i such that x == y[i],and all lower integer indices do not raise IndexError exception. (If any other exception is raised,it is as if in raised that exception).

例证:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读