Python,我应该基于__eq__实现__ne __()运算符吗? [英] Python, should I implement __ne__() operator based on __eq__?

查看:2533
本文介绍了Python,我应该基于__eq__实现__ne __()运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我要覆盖 __ eq __()运算符。似乎有意义的是,我应该重写 __ ne __()运算符,但它是有意义的实现 __ ne __ __ eq __ 如此?

I have a class where I want to override the __eq__() operator. It seems to make sense that I should override the __ne__() operator as well, but does it make sense to implement __ne__ based on __eq__ as such?

class A:
    def __eq__(self, other):
        return self.value == other.value

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

或者有些东西,我错过了Python使用这些运算符,好主意?

Or is there something that I'm missing with the way Python uses these operators 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__:


$ b的比较运算符。 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.

这篇关于Python,我应该基于__eq__实现__ne __()运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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