弦的第一个奥秘:
为什么bool('foo')
返回True
?
if
'foo' == True
returnsFalse
'foo' == False
returnsFalse
'foo' is True
returnsFalse
'foo' is False
returnsFalse
第二个整数之谜:
为什么bool(5)
返回True
?
if
5 == True
returnsFalse
5 == False
returnsFalse
5 is True
returnsFalse
5 is False
returnsFalse
第三个零之谜:
为什么bool(0)
返回False
?
if
0 == True
returnsFalse
0 == False
returnsTrue
<-- Special Case0 is True
returnsFalse
0 is False
returnsFalse
我知道Python的一些真实性,然而,这一切似乎有点神秘。有人能解释一下吗?你知道吗
你需要读一下:https://docs.python.org/2/library/stdtypes.html#truth-value-testing
总是
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?
这是因为
0
和''
在Python中都是False
,而非空字符串和非零整数都是真的。你知道吗在您的所有示例中,它们从您的期望返回的原因是
==
检查相同的value
,而is
检查两者是否指向相同的对象。你知道吗所以在第一种情况下,
foo
是True
,但它们不是相同的值。另外,foo
与True
指向的值不同,这就是它返回false的原因。其余的示例继续使用相同的模式。你知道吗相关问题 更多 >
编程相关推荐