Skip to main content
 首页 » 编程设计

python之重写一个类成为 in 运算符的左侧

2025年04月02日8yjmyzz

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

请您参考如下方法:

我能够通过覆盖 __eq__ 来让它工作。

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

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