根据“Python docs:”定义__eq__()
时,还应定义__ne__()
,以便操作员的行为符合预期”。
但是,似乎python会自动将__ne__
计算为not __eq__
:
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)
?而且,这种行为在哪里被记录下来呢?编辑
显然,使用Python3很重要。在python 2中,我得到
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文档。他们只是没有更新吗?
最佳答案
python 3更改了==
案例的行为,请参见Python 3, What's New:!=
现在返回与==
相反的值,除非==
返回NotImplemented
。
它被认为是a useful change。
文档尚未更新的事实实际上是一个long standing bug。
但是,正如对报告的注释所指出的那样,如果您继承了一个已经定义了__ne__
的类,那么仅仅重写__eq__
是不够的,您还必须重写__ne__
方法。
关于python - 为什么Python文档说我在定义__eq__时需要定义__ne__?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24455406/