回答
答案解釋here。
引述:
類是自由地實現 比較它選擇的任何方式,它 可以選擇讓對 無對比意味着什麼(這實際上 是有道理的,如果有人告訴你到 執行None對象從 從頭開始,你會怎麼得到它 比較自己?)。
實際上,自定義比較運算符很少出現,沒有太大的區別。但是您應該使用is None
作爲一般規則。
這是一個有趣的(和簡短)閱讀。還有一些有用的信息進入'is' v。'=='。 – 2010-07-15 16:59:58
另外,'None'比'== None'快一點(〜50%):) – 2010-07-16 01:08:35
@NasBanov你有鏈接到你讀的地方嗎? – myusuf3 2012-01-25 20:12:02
在這種情況下,它們是相同的。 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"
這個答案不正確,正如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
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False
如果使用numpy的,
if np.zeros(3)==None: pass
會給時numpy的做的elementwise比較
- 1. 「Future.successful(None)」和「Future(None)」之間的區別是什麼
- 2. 熊貓:NaN和None之間的區別
- 3. access =「permitAll」和filters =「none」之間的區別?
- 4. BorderStyle = NotSet和BorderStyle = None之間的區別
- 5. NaN和None有什麼區別?
- 6. 爲什麼str(None)不是str(None)?
- 7. jQuery的hide()和.css('display','none')之間的區別?
- 8. RxSwift中的asObserver,asObservable和none之間的區別
- 9. Is List :: MoreUtils :: none buggy?
- 10. 'await future'和'await asyncio.wait_for(future,None)'之間有區別嗎?
- 11. Numpy.array(None)返回None但不是None
- 12. 爲什麼class .__ weakref__不是None,而instance .__ weakref__是None?
- 13. 「x IS NULL」和「NOT(x IS NOT NULL)」之間的區別是什麼?
- 14. ++和:haskell之間的區別是什麼?
- 15. [undefined]和[,]之間的區別是什麼?
- 16. .equals()和==之間的區別是什麼?
- 17. arm-linux-gcc和arm-none-linux-gnueabi有什麼區別
- 18. is和=有什麼區別?
- 19. `==`和`is`有什麼區別?
- 20. $(())和expr之間的區別是什麼?
- 21. $和$ .fn之間的區別是什麼?
- 22. $(「」)和$ .find(「」)之間的區別是什麼?
- 23. 「\」和「\。」之間的區別是什麼?
- 24. 「$ | ++」和「$ | = 1」之間的區別是什麼
- 25. $(...)和`...`之間的區別是什麼
- 26. Python'if x is None'not catch NoneType None
- 27. int和none類型之間的python nonetype
- 28. Swift is和isKindOfClass()之間的區別?
- 29. Python:`is`和`==`之間的區別?
- 30. MVC和MVVM之間的區別和相似之處是什麼?
看你錯誤[有間'=='和'is' Python中的區別嗎?] (http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python/134659#134659) – 2010-07-15 16:58:50
@ myusuf3:你可能想考慮改變接受的答案正確的一個。 – max 2012-01-24 19:12:18