在python2中获得对丰富比较运算符的更多控制

时间:2015-12-31 06:04:15

标签: python python-2.x

>>> class Yeah(object):
...     def __eq__(self, other):
...         return True
...     
>>> class Nah(object):
...     def __eq__(self, other):
...         return False
...     
>>> y = Yeah()
>>> n = Nah()
>>> y == n
True
>>> n == y
False

左边的人赢了,因为当python2看到x == y时,它首先尝试x.__eq__(y)

有没有办法修改Nah以便他两次都赢?

我的用例是这样的:

class EqualsAnyDatetime(object):
    def __eq__(self, other):
        return isinstance(other, datetime)

它只适用于python3,因为real_datetime.__eq__(random_other_thing)引发了NotImplemented,让对方在比较中获得了一个机会。在python2中我似乎无法理解这个想法。

2 个答案:

答案 0 :(得分:1)

不,你不能这样做。始终首先尝试左侧操作数。如果它处理操作,右手操作数永远不会有机会做任何事情。

答案 1 :(得分:1)

我找到了一种方法可以让右手有机会先说出我#34;诀窍是从你希望强化比较的类型继承。

示例:

>>> from datetime import datetime
>>> class EqualsAnyDatetime(datetime):
...     def __eq__(self, other):
...         return isinstance(other, datetime)
...     
>>> now = datetime.now()
>>> any_datetime = EqualsAnyDatetime(1970, 1, 1)
>>> now == any_datetime
True
>>> any_datetime == now
True
>>> now.__eq__(any_datetime)
False