2013-10-11 155 views
0

這可能是非常基本的,但:在python 2.7「x!= y」和「not x == y」之間有什麼區別?

是同一類的XY對象,調用not x == y會導致我的調試器停止類__eq__方法,但調用x != y不會?

!=檢查什麼?是否相當於is not(參考檢查)?

+1

無論如何,'=='和'is'是不相同的。見例如http://stackoverflow.com/a/2988271/599884 – Christoph

+1

我的意思是,爲自己嘗試。 'a = list(); b = list();打印a是b;打印a == b' – roippi

回答

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)) 
5

從這個頁面引用,http://docs.python.org/2/reference/datamodel.html#object.ne

有比較運營商之間沒有隱含的關係。 x==y的 的真值並不意味着x!=y是錯誤的。因此,當 定義爲__eq__()時,還應該定義__ne__(),以便運營商將按照預期行事。請參閱__hash__()的段落 關於創建支持自定義 比較操作的可排序對象的一些重要注意事項,並且可用作字典鍵。

相關問題