在python 2.7中,"x!= y"和"not x == y"之间的区别是什么?

hit*_*wen 0 python python-2.7

这可能是非常基本但是:

作为XY同一个类的对象,调用not x == y会导致我的调试器停止类__eq__的方法,但调用x != y不会?

是什么!=检查?它等同于is not(参考检查)吗?

use*_*342 8

!=运营商调用__ne__特殊的方法.定义的类也__eq__应该定义一个__ne__反向的方法.

提供典型的模式__eq__,__ne____hash__看起来像这样:

class SomeClass(object):
    # ...
    def __eq__(self, other):
        if not isinstance(other, SomeClass):
            return NotImplemented
        return self.attr1 == other.attr1 and self.attr2 == other.attr2

    def __ne__(self, other):
        return not (self == other)

    # if __hash__ is not needed, write __hash__ = None and it will be
    # automatically disabled
    def __hash__(self):
        return hash((self.attr1, self.attr2))
Run Code Online (Sandbox Code Playgroud)


the*_*eye 5

从此页面引用http://docs.python.org/2/reference/datamodel.html#object.NE

比较运算符之间没有隐含的关系.事实x==y并非暗示这x!=y是错误的.因此,在定义时__eq__(),还应该定义__ne__()操作符将按预期运行.有关__hash__()创建支持自定义比较操作的可哈希对象的一些重要说明,请参阅段落,并可用作字典键.