2010-07-15 133 views
186

我最近遇到這個語法,我不知道其中的差別。「is None」和「== None」之間的區別是什麼

如果有人能告訴我不同​​之處,我將不勝感激。

+2

看你錯誤[有間'=='和'is' Python中的區別嗎?] (http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python/134659#134659) – 2010-07-15 16:58:50

+0

@ myusuf3:你可能想考慮改變接受的答案正確的一個。 – max 2012-01-24 19:12:18

回答

177

答案解釋here

引述:

類是自由地實現 比較它選擇的任何方式,它 可以選擇讓對 無對比意味着什麼(這實際上 是有道理的,如果有人告訴你到 執行None對象從 從頭開始,你會怎麼得到它 比較自己?)。

實際上,自定義比較運算符很少出現,沒有太大的區別。但是您應該使用is None作爲一般規則。

+0

這是一個有趣的(和簡短)閱讀。還有一些有用的信息進入'is' v。'=='。 – 2010-07-15 16:59:58

+17

另外,'None'比'== None'快一點(〜50%):) – 2010-07-16 01:08:35

+0

@NasBanov你有鏈接到你讀的地方嗎? – myusuf3 2012-01-25 20:12:02

38

在這種情況下,它們是相同的。 None是一個單身物件(只存在一個None)。

is檢查對象是否是同一個對象,而==只是檢查它們是否相同。

例如:

p = [1] 
q = [1] 
p is q # False because they are not the same actual object 
p == q # True because they are equivalent 

但由於只有一個None,他們永遠是相同的,並且is將返回true。

p = None 
q = None 
p is q # True because they are both pointing to the same "None" 
+14

這個答案不正確,正如Ben Hoffstein在http://stackoverflow.com/questions/3257919/is-none-vs-none/3257957#3257957下的回答所解釋的那樣。即使「x」不是「None」,「x == None」也可以評估爲「True」,但是某些類的實例具有自己的自定義相等運算符。 – max 2010-11-16 03:00:04

91
class Foo: 
    def __eq__(self,other): 
     return True 
foo=Foo() 

print(foo==None) 
# True 

print(foo is None) 
# False 
3

如果使用numpy的,

if np.zeros(3)==None: pass 

會給時numpy的做的elementwise比較

相關問題