2015-09-05 122 views
-1

字符串的一個疑團:
爲什麼bool('foo')返回True
神祕案件,和對象標識符

如果
'foo' == True回報False
'foo' == False回報False
'foo' is True回報False
'foo' is False返回False

整數的第二個祕密:
bool(5)怎麼回來True

如果
5 == True回報False
5 == False回報False
5 is True回報False
5 is False回報False

的第三個謎:
怎麼來bool(0)返回False

如果
0 == True返回False
0 == False回報True < - 特例
0 is True返回False
0 is False回報False

我意識到Python的一些真實性,但是,這一切似乎有點神祕。有人介意在這方面解釋一些情況嗎?

+0

[真值測試](https://docs.python.org/2/library/stdtypes.html#truth-value-testing) –

回答

2

你需要閱讀這一點:https://docs.python.org/2/library/stdtypes.html#truth-value-testing

'foo' == True # -> False 
'' == True  # -> False 
'' == False # -> False 

永遠是False。一個字符串不等於bool。但 - 是的 - bool('non-empty-str') -> True; bool('') -> False

等等爲你其他'奧祕'。

is比較認同兩個對象的id()(有一些奧祕這裏還有:What's with the Integer Cache inside Python?

也可能是有趣的:Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

2

這是因爲這兩個0''在Python False,而非空字符串和非零整數爲真。

在你所有的例子中,他們從你的期望中返回的原因是因爲==檢查相同的valueis檢查兩個指向同一個對象。

因此在第一種情況下,fooTrue,但它們不是相同的值。同樣,foo未指向與True相同的值,因此它返回false。剩下的例子繼續使用相同的模式。