在自定义类中搜索包含和 iter

为了允许将 in 用于自定义类,该类必须提供魔术方法 __contains__,否则提供 __iter__ 方法。

假设你有一个包含 list of lists 的类:

class ListList:
    def __init__(self, value):
        self.value = value
        # Create a set of all values for fast access
        self.setofvalues = set(item for sublist in self.value for item in sublist)
        
    def __iter__(self):
        print('Using __iter__.')
        # A generator over all sublist elements
        return (item for sublist in self.value for item in sublist)
        
    def __contains__(self, value):
        print('Using __contains__.')
        # Just lookup if the value is in the set
        return value in self.setofvalues

        # Even without the set you could use the iter method for the contains-check:
        # return any(item == value for item in iter(self))

使用 in 可以使用成员资格测试:

a = ListList([[1,1,1],[0,1,1],[1,5,1]])
10 in a    # False
# Prints: Using __contains__.
5 in a     # True
# Prints: Using __contains__.

甚至在删除 __contains__ 方法后:

del ListList.__contains__
5 in a     # True
# Prints: Using __iter__.

注意: 循环 in(如 for i in a 中)将始终使用 __iter__,即使该类实现了 __contains__ 方法。