为什么python中有一个不相等的运算符

mag*_*gu_ 9 python operator-overloading python-3.x

我想知道有一个不平等的运营商的原因python.

以下剪辑:

class Foo:
    def __eq__(self, other):
        print('Equal called')
        return True

    def __ne__(self, other):
        print('Not equal called')
        return True

if __name__ == '__main__':
    a = Foo()

    print(a == 1)
    print(a != 1)
    print(not a == 1)
Run Code Online (Sandbox Code Playgroud)

输出:

Equal called
True
Not equal called
True
Equal called
False
Run Code Online (Sandbox Code Playgroud)

这实际上是否可能会引发很多麻烦:

A == B and A != B
Run Code Online (Sandbox Code Playgroud)

可以同时正确.此外,这在忘记实施时引入了潜在的缺陷__ne__.

Eth*_*man 7

根据一个人的需要,有些情况是平等和不平等不相反; 但是,绝大多数情况下它们都是相反的,所以在Python 3中如果你没有指定__ne__方法,Python会__eq__为你反转方法.

如果您要编写代码以在Python 2和Python 3上运行,那么您应该同时定义它们.


J_B*_*J_B -2

看来你是在返回True而不是进行比较。

  • 他的代码片段实际上并没有问题。他问为什么语言是这样设计的。 (3认同)