看起来 if x
几乎就像是 if x is not None
更长的简写语法。它们在功能上是完全相同的,还是在某些情况下对于给定的 x
值,两者会有不同的计算结果?
我认为这种行为在Python的各种实现中应该也是相同的,但如果有微妙的差异,那就很好了解。
在以下情况下:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()
if语句中的if
测试会有所不同:
if test: #False
if test is not None: #True
这是因为is
测试的是身份(identity),意味着
test is not None
等价于
id(test) == id(None) #False
因此
(test is not None) is (id(test) != id(None)) #True
前者测试真实性,而后者测试与None
的身份是否相同。许多值为假,例如False
,0
,''
和None
,但只有None
是None
。
注:Trueness指的是一个值在布尔上下文中被认为是“真”的能力,而不是它的实际身份(如对象引用)。例如,非零数字在布尔上下文中被视为True,尽管它们的身份可能不同。
x = 0
if x: ... # False
if x is not None: ... # True
if x
检查 x
是否被视为 True
。
在 Python 中,所有的值都有一个布尔值 (True
/False
)。
被视为 False
的值包括:
False
, None
0
, 0.0
, 0j
[]
, ()
, {}
''
其他值被视为 True
。例如,[False]
、('hello')
、'hello'
被视为 True
(因为它们不是空的)。
当使用 if x is not None
时,您正在检查 x
是否不是 None
,但它可能是 False
或其他被视为 False
的实例。
>>> x = None
>>> if not x:print x # bool(None) is False
None
>>> if x == None:print x
None
>>> x = False
>>> if not x:print x
False
>>> if x == None:print x
最后,请注意True
和False
分别等于1
和0
:
>>> True + 1
2
>>> False + 1
1
>>> range(1, 5)[False]
1
if x:
# Evaluates for any defined non-False value of x
if not x:
# Evaluates for any defined False value of x
if x is None:
# Evaluates for any instances of None
None不是它自己的类型,它恰好等于False。"if not x" 语句只有在x=None时才会成立,因为None等同于False。
我不知道是否存在微妙的区别,但确实有一些精确的方法可以在特定情况下测试正/负性。在某些情况下混用它们可能有效,但如果不理解它们会导致问题。
if x is True:
# Use for checking for literal instances of True
if x is False:
# Use for checking for literal instances of False
if x is None:
# Use for checking for literal instances of None
if x:
# Use for checking for non-negative values
if not x:
# Use for checking for negative values
# 0, "", None, False, [], (), {} are negative, all others are True
__bool__
或__nonzero__
并返回false的内容。 - Autoplectic