当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
点赞