为什么Python文档说我在定义__eq__时需要定义__ne__? [英] Why do the Python docs say I need to define __ne__ when I define __eq__?

查看:85
本文介绍了为什么Python文档说我在定义__eq__时需要定义__ne__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Python文档:在定义__eq__(),还应该定义__ne__(),以便操作员可以按预期方式工作."

According to the Python docs: "when defining __eq__(), one should also define __ne__() so that the operators will behave as expected".

但是,似乎Python自动将__ne__计算为not __eq__:

However, it appears that Python computes __ne__ as not __eq__ automatically:

In [8]: class Test:
    def __eq__(self, other):
        print("calling __eq__")
   ...:         return isinstance(other, Test)
   ...:

In [9]: a = Test()

In [10]: b = Test()

In [11]: a == b
calling __eq__
Out[11]: True

In [12]: a != b
calling __eq__
Out[12]: False

In [13]: a == 1
calling __eq__
Out[13]: False

In [14]: a != 1
calling __eq__
Out[14]: True

那么定义__ne__如果只是return not self.__eq__(other)有什么意义呢?而且,这种行为实际记录在哪里?

So what's the point of defining __ne__ if it's just going to be return not self.__eq__(other)? And furthermore, where is this behavior actually documented?

编辑

显然,使用Python 3很重要.在Python 2中,我得到了

Apparently it matters that I am using Python 3. In Python 2, I get

In [1]: class Test(object):
   ...:     def __eq__(self, other):
   ...:         print("calling __eq__")
   ...:         return isinstance(other, Test)
   ...:

In [2]: a = Test()

In [3]: b = Test()

In [4]: a == b
calling __eq__
Out[4]: True

In [5]: a != b
Out[5]: True

In [6]: a == 1
calling __eq__
Out[6]: False

In [7]: a != 1
Out[7]: True

但是我引用的文档是Python 3文档.他们只是没有更新吗?

But the docs I referenced are the Python 3 docs. Were they just not updated?

推荐答案

==情况下,Python 3更改了行为,请参见

Python 3 changed behaviour for the == case, see Python 3, What's New:

!=现在返回与==相反的结果,除非==返回NotImplemented.

!= now returns the opposite of ==, unless == returns NotImplemented.

它被认为是有用的更改.

文档尚未更新的事实确实是长期存在的错误.

The fact that the documentation has not been updated is indeed a long standing bug.

但是,正如对报告的评论所指出的那样,如果您从已经定义了__ne__的类继承,则仅覆盖__eq__是不够的,并且您还必须覆盖__ne__方法.

However, as a comment on the report points out, if you inherit from a class that already has defined __ne__, overriding just __eq__ is not enough and you'll also have to override the __ne__ method.

这篇关于为什么Python文档说我在定义__eq__时需要定义__ne__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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