Skip to main content
 首页 » 编程设计

python之更好地控制 python2 中丰富的比较运算符

2024年10月24日9jiqing9006

>>> 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 中,我似乎无法实现这个想法。

请您参考如下方法:

不,你不能那样做。左边的操作数总是首先尝试。如果它处理该操作,则右侧操作数永远没有机会做任何事情。