【发布时间】:2010-10-10 16:33:35
【问题描述】:
似乎“if x”几乎是较长的“if x is not None”语法的简写。它们在功能上是相同的,还是在某些情况下,对于给定的 x 值,两者的评估方式不同?
我会假设 Python 实现的行为也应该是相同的 - 但如果有细微的差异,那就太好了。
【问题讨论】:
似乎“if x”几乎是较长的“if x is not None”语法的简写。它们在功能上是相同的,还是在某些情况下,对于给定的 x 值,两者的评估方式不同?
我会假设 Python 实现的行为也应该是相同的 - 但如果有细微的差异,那就太好了。
【问题讨论】:
以下情况:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()
if 测试会有所不同:
if test: #False
if test is not None: #True
之所以如此,是因为is 测试身份,意义
test is not None
等价于
id(test) == id(None) #False
因此
(test is not None) is (id(test) != id(None)) #True
【讨论】:
__bool__ 或__nonzero__ 返回false。
前者测试真实性,而后者测试与None 的身份。很多值都是假的,比如False、0、''和None,但只有None是None。
【讨论】:
x = 0
if x: ... # False
if x is not None: ... # True
【讨论】:
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
【讨论】:
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
【讨论】: