Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
后两者之一,因为
val
可能是定义__eq__()
的类型,以便在传递None
时返回true。是测试变量未设置为
None
的Pythonic习惯用法。这个习语在declaring keyword functions with default parameters的情况下有特殊的用途。is
在Python中测试标识。因为运行的Python脚本/程序中只存在一个None
实例,is
是对此的最佳测试。作为Johnsyweb points out,这在PEP 8“编程建议”下讨论。至于为什么这是首选
这只是Zen of Python“可读性很重要”的一部分,好的Python通常接近好的pseudocode。
来自,编程建议,PEP 8:
PEP 8对于任何Python程序员来说都是必不可少的读物。
相关问题 更多 >
编程相关推荐