在自定義類中搜尋包含和 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__ 方法。