__ne__是否应在Python中实现为__eq__的否定形式? [英] Should __ne__ be implemented as the negation of __eq__ in Python?

查看:61
本文介绍了__ne__是否应在Python中实现为__eq__的否定形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要覆盖 __ 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. Should I implement __ne__ as the negation of __eq__ as such or is it a bad idea?

class A:

    def __init__(self, state):
        self.state = state

    def __eq__(self, other):
        return self.state == other.state

    def __ne__(self, other):
        return not self.__eq__(other)

推荐答案

是的,这很好.实际上,文档敦促您定义 __ ne __ __ eq __ 时的code>:

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 that x!=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.

这篇关于__ne__是否应在Python中实现为__eq__的否定形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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