将一个类重写为运算符的左侧

时间:2016-10-01 01:49:41

标签: python contains

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

1 个答案:

答案 0 :(得分:1)

我能够通过覆盖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