在 Python 中不是 None 测试 [英] not None test in Python
问题描述
在这些非无测试中.
if val != None:
if not (val is None):
if val is not None:
哪个更可取,为什么?
推荐答案
if val is not None:
# ...
是 Pythonic 习惯用法,用于测试变量未设置为 None
.这个习语在使用默认参数声明关键字函数的情况下有特殊用途.is
在 Python 中测试身份.因为在运行的 Python 脚本/程序中只有一个 None
实例,is
是对此的最佳测试.正如 Johnsyweb 指出的,这在 PEP 8 在编程建议"下.
is the Pythonic idiom for testing that a variable is not set to None
. This idiom has particular uses in the case of declaring keyword functions with default parameters. is
tests identity in Python. Because there is one and only one instance of None
present in a running Python script/program, is
is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".
至于为什么这是首选
if not (val is None):
# ...
这只是 Python 之禅的一部分:可读性很重要."好的 Python 通常接近好的 伪代码.
this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.
这篇关于在 Python 中不是 None 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!