<p>来自<a href="http://docs.python.org/py3k/reference/executionmodel.html">python doc</a>的<strong>局部/全局/自由变量定义:</p>
<blockquote>
<p>If a name is bound in a block, it is a <strong>local variable</strong> of that block, unless declared as nonlocal. If a name is bound at the module level, it is a <strong>global variable</strong>. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a <strong>free variable</strong>.</p>
</blockquote>
<hr/>
<h3>代码1:</h3>
<pre><code>>>> x = 0
>>> def foo():
... print(x)
... print(locals())
...
>>> foo()
0
{}
</code></pre>
<hr/>
<h3>代码2:</h3>
<pre><code>>>> def bar():
... x = 1
... def foo():
... print(x)
... print(locals())
... foo()
...
>>> bar()
1
{'x':1}
</code></pre>
<p><sub><strong>当自由变量在函数块中调用而不是在类块中调用时,由<code>locals()</code>返回。</sub></p>
<hr/>
<p>在<code>Code 1</code>中,<code>x</code>是一个<strong>全局变量,它在<code>foo()</code>中使用但未定义。<br/>
但是它不是一个自由变量,因为它不是由<code>locals()</code>返回的。<br/>
我想不是医生说的。是否有自由变量的技术定义?</p>