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