3 回答

TA贡献1744条经验 获得超4个赞
这些实际上都是不良做法。曾几何时,认为随意对待None和False是相似的。但是,从Python 2.2开始,这不是最好的策略。
首先,当你进行一种if x或if not x那种测试时,Python必须隐式转换x为boolean。bool函数的规则描述了一大堆错误的东西; 其他一切都是真的。如果x的值在开始时没有正确的布尔值,那么这种隐式转换实际上并不是最清楚的说法。
在Python 2.2之前,没有bool函数,所以它更不清楚。
其次,你不应该真的测试== None。你应该使用is None和is not None。
请参阅PEP 8,Python代码样式指南。
- 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!
有多少单身人士?五:None,True,False,NotImplemented和Ellipsis。因为你真的不太可能使用NotImplemented或者Ellipsis,你永远不会说if x is True(因为只是if x更清楚),你只会测试None。
添加回答
举报