擅长:python、mysql、java
<p>只有在全局(模块)范围之外引用变量时才会引入闭包:</p>
<pre><code>>>> def foo():
... def bar(): pass
... return bar
...
>>> foo().func_closure is None
True
>>> spam = 'eggs'
>>> def foo():
... def bar(): return spam
... return bar
...
>>> foo().func_closure is None
True
</code></pre>
<p>只有当内部函数引用周围范围内的变量时,才会生成闭包:</p>
^{pr2}$
<p>请注意,实际上必须引用周围范围中的变量。简单地忽略作用域会再次给您<code>None</code>:</p>
<pre><code>>>> def foo():
... spam = 'eggs'
... def bar(): pass
... return bar
...
>>> foo().func_closure is None
True
</code></pre>
<p>在第一个示例中,<code>i</code>是一个模块范围变量,只有在第二个示例中,才会通过将代码包装在新函数<code>actualFact</code>中来引入新的范围。在</p>