问题描述
>>>类呀(对象):... def __eq__(self, other):...返回真...>>>类 Nah(对象):... def __eq__(self, other):...返回假...>>>y = 是的()>>>n = 不()>>>y == n真的>>>n == y错误的左边的人赢了,因为当python2看到x == y
时,它首先尝试x.__eq__(y)
.
有没有办法修改Nah
,让他两次都赢?
我的用例是这样的:
class EqualsAnyDatetime(object):def __eq__(自我,其他):返回 isinstance(其他,日期时间)
它只适用于 python3,因为 real_datetime.__eq__(random_other_thing)
引发 NotImplemented
,让对方有机会进行比较.在 python2 中,我似乎无法理解这个想法.
我找到了一种方法,可以让右手边有机会说我先".诀窍是从您想要与之进行比较的类型继承.
示例:
>>>从日期时间导入日期时间>>>类等于AnyDatetime(日期时间):... def __eq__(self, other):...返回 isinstance(other, datetime)...>>>现在 = datetime.now()>>>any_datetime = EqualsAnyDatetime(1970, 1, 1)>>>现在 == any_datetime真的>>>any_datetime == 现在真的>>>现在.__eq__(any_datetime)错误的>>> 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.
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
这篇关于更好地控制python2中丰富的比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!