如何缩短 if 语句中的 "is not None"
How to shorten the "is not None" in the if statement
在Python3中,PEP8中的Truth Value Testing
说对于if A is None:
,可以转换为if not A:
。像这样,既然下面的代码看起来很乱,很难一下子掌握,那么能不能用这种或那种方式表达得更简洁一点呢?
if A is not None and B is not None and C is not None:
any() 和 all() 也可以与理解一起使用,以在这些情况下提供帮助。
if all([x is not None for x in [A,B,C]]):
我同意 superbeck 使用 any()
或 all()
,但您也可以检查 None
是否存在于包含 A
、B
、C
if not (None in [A,B,C]):
或更直观地 if None not in [A, B, C]:
(Blckknght)
旁注(更深入的研究)
无论哪种方式,我都不鼓励使用 if A and B and C:
,因为 if A is not None
和 if A
做不同的事情。
if A:
调用 A.__nonzero__()
并使用该函数的 return 值。
if A is not None
是在Python中测试身份。因为在 运行 Python script/program
中只有一个 None 实例
检查这个post and this post
在Python3中,PEP8中的Truth Value Testing
说对于if A is None:
,可以转换为if not A:
。像这样,既然下面的代码看起来很乱,很难一下子掌握,那么能不能用这种或那种方式表达得更简洁一点呢?
if A is not None and B is not None and C is not None:
any() 和 all() 也可以与理解一起使用,以在这些情况下提供帮助。
if all([x is not None for x in [A,B,C]]):
我同意 superbeck 使用 any()
或 all()
,但您也可以检查 None
是否存在于包含 A
、B
、C
if not (None in [A,B,C]):
或更直观地 if None not in [A, B, C]:
(Blckknght)
旁注(更深入的研究)
无论哪种方式,我都不鼓励使用 if A and B and C:
,因为 if A is not None
和 if A
做不同的事情。
if A:
调用 A.__nonzero__()
并使用该函数的 return 值。
if A is not None
是在Python中测试身份。因为在 运行 Python script/program
检查这个post and this post