Getting more control over the rich comparison operators in python2

北慕城南 提交于 2019-12-22 14:07:12

问题


>>> 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

The left guy wins because when python2 sees x == y it tries x.__eq__(y) first.

Is there any way to modify Nah so that he will win both times?

My use-case is making something like this:

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

It just works in python3 because real_datetime.__eq__(random_other_thing) raises NotImplemented, giving the other side a shot at the comparison. In python2 I can't seem to get the idea working.


回答1:


No, you cannot do that. The left-hand operand is always tried first. If it handles the operation, the right-hand operand never gets a chance to do anything.




回答2:


I've found a way that can give the right hand side the opportunity to say "me first". The trick is to inherit from the type(s) who you want to strong-arm the comparison against.

Example:

>>> 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


来源:https://stackoverflow.com/questions/34541894/getting-more-control-over-the-rich-comparison-operators-in-python2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!