更好地控制python2中丰富的比较运算符 [英] Getting more control over the rich comparison operators in python2

查看:29
本文介绍了更好地控制python2中丰富的比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>类呀(对象):... 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中丰富的比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆