我是否应该在__eq__中用python实现__ne__? [英] Should I implement __ne__ in terms of __eq__ in Python?
问题描述
我有一个要覆盖 __ eq __
方法的类。我也应该重写 __ ne __
方法似乎很有意义,但是在其中实现 __ ne __
是否有意义 __ eq __
这样的术语?
I have a class where I want to override the __eq__
method. It seems to make sense that I should override the __ne__
method as well, but does it make sense to implement __ne__
in terms of __eq__
as such?
class A:
def __init__(self, attr):
self.attr = attr
def __eq__(self, other):
return self.attr == other.attr
def __ne__(self, other):
return not self.__eq__(other)
还是Python使用这些方法的方式使我不满意?
Or is there something that I am missing with the way Python uses these methods that makes this not a good idea?
推荐答案
是的,这很好。实际上,文档敦促您定义 __ne __
定义 __ eq __
时:
Yes, that's perfectly fine. In fact, the documentation urges you to define __ne__
when you define __eq__
:
比较运算符之间没有隐含的关系
。x == y
的
真相并不表示x!= y
是假。因此,在定义
__ eq __()
时,还应定义__ ne __()
,以便操作员将
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false. Accordingly, when defining__eq__()
, one should also define__ne__()
so that the operators will behave as expected.
在很多情况下(例如这种情况),只要将 __ eq __
,但并非总是如此。
In a lot of cases (such as this one), it will be as simple as negating the result of __eq__
, but not always.
这篇关于我是否应该在__eq__中用python实现__ne__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!