<p>这实际上都是不好的做法。曾几何时,人们认为随便地把“无”和“假”当作相似的东西是可以的。但是,由于Python2.2,这不是最好的策略。</p>
<p>首先,在进行<code>if x</code>或<code>if not x</code>类型的测试时,Python必须隐式地将<code>x</code>转换为布尔值。函数<code>bool</code>的规则描述了大量的错误;其他的都是正确的。如果x的值一开始不是正确的布尔值,那么这种隐式转换并不是最清晰的表达方式。</p>
<p>在Python2.2之前,没有bool函数,所以它就更不清晰了。</p>
<p>第二,您不应该真正使用<code>== None</code>进行测试。您应该使用<code>is None</code>和<code>is not None</code>。</p>
<p>见政治公众人物8,<a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">Style Guide for Python Code</a>。</p>
<blockquote>
<pre><code>- 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!
</code></pre>
</blockquote>
<p>有多少单身汉?五:<code>None</code>,<code>True</code>,<code>False</code>,<code>NotImplemented</code>和<code>Ellipsis</code>。因为您不太可能使用<code>NotImplemented</code>或<code>Ellipsis</code>,而且您永远不会说<code>if x is True</code>(因为<code>if x</code>更清楚),所以您将只测试<code>None</code>。</p>