<blockquote>
<p>Is there any difference between these three in a specific scenario ?</p>
</blockquote>
<p>第一个问题是变量是否有错误。除了<code>None</code>-<code>False</code>、<code>0</code>和任何空序列等,此测试将失败</p>
<p>第二个问题是它是否是神奇的单重常数<code>None</code>。这只会对<code>None</code>本身失败。</p>
<p>第三个问题是它是否认为自己等于<code>None</code>。这将失败,比如说,<code>Holder(None)</code>,其中<code>Holder</code>是一个包装类,其实例与它们所持有的内容进行比较。或者,给出一个不太现实但代码更短的exmaple:</p>
<pre><code>class Stupid(object):
def __ne__(self, other):
return False
Variable = Stupid()
</code></pre>
<p>最后一个是很少有用的;事实上,如果您认为可能需要检查<code>== None</code>或<code>!= None</code>,并且您没有专门创建透明包装类或类似的类,那么您可能实际上需要<code>is None</code>或<code>is not None</code>。但另外两个都是非常有用和常见的。</p>
<blockquote>
<p>if there is no difference which one is more suitable to use?</p>
</blockquote>
<p>嗯,有一个区别,哪一个更合适取决于具体的用途。</p>
<p>在问题的最后,您可能会问,在<code>Variable</code>肯定是<code>None</code>的特定情况下,是否存在任何差异。在这种情况下,三者之间当然没有功能上的区别,*它们都保证是错误的,因此什么也不做。这意味着这三种方法中的任何一种都和不写代码没有区别。更简单,可读性更强,速度更快。</p>
<p>*有一个性能差异第一个不需要<code>LOAD_CONST</code>和<code>None</code>,也不需要调用比较运算符。而且,即使您以某种方式重新绑定了<code>None</code>或更改了<code>None</code>常量的值(可能是用<code>ctypes</code>在堆中到处跺脚?),第一个更可能仍然有效。但这两种方法都不重要,如果它们真的重要,那么任何代码都不会更快、更可靠。</p>