将 class 重写为 in 运算符的左侧

Overriding a class to be left hand side of in operator

显然,当具有该方法的对象位于它的右侧时,__contains__ 特殊方法允许实现 in 求值。我有一段代码,其中 in 必须由左侧操作数实现。我该怎么做?

我能够通过重写 __eq__.

来让它工作

考虑代码“some_list 中的值”。它将遍历 some_list 直到找到值。但是它怎么知道它是否找到了价值呢?通过比较。这就是您要覆盖的内容。

class Twenty(object):
    def __init__(self):
        self.x = 20
            
    def __eq__(self, y):
        print "comparing", self.x, "to", y
        return self.x == y
    
value = Twenty()
assert value in [10, 20, 30]
assert value not in [1, 2, 3]

输出

comparing 20 to 10
comparing 20 to 20
comparing 20 to 1
comparing 20 to 2
comparing 20 to 3