微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当python的`in`函数通过`__getitem __()`’触发时,它是如何工作的?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐