Should I implement __ne__ as the negation of __eq__ in Python?

后端 未结 5 1921
无人共我
无人共我 2020-11-27 11:55

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. Should I implem

5条回答
  •  孤独总比滥情好
    2020-11-27 12:29

    Yes, that's perfectly fine. In fact, the documentation urges you to define __ne__ when you define __eq__:

    There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected.

    In a lot of cases (such as this one), it will be as simple as negating the result of __eq__, but not always.

提交回复
热议问题