<p>当Python创建扫描其主体的函数时,所有事情都会发生:</p>
<pre><code>def foo():
def bar():
print(locals()) # P is not present
print(y)
print(y)
x = 5
print(locals()) # after initializing x is added to local
y = 1
p = 1
# ('x',) local variables
print(bar.__code__.co_varnames)
# ('y',) non local variables used by the function
print(bar.__code__.co_freevars)
bar()
foo()
</code></pre>
<p>Python发现<code>bar</code>使用了<code>y</code>,但是它在body函数的任何一点上都没有初始化,所以它是<code>co_freevars</code>:</p>
<blockquote>
<p>co_freevars : tuple of names of free variables (referenced via a
function’s closure</p>
</blockquote>
<p>位于assiegment表达式左侧的其他变量是<code>co_varnames</code></p>
<blockquote>
<p>co_varnames : tuple of names of arguments and local variables</p>
</blockquote>
<p>当您使用global时,您告诉Python这不是一个局部变量,当
你改变了它的值,你改变了它的全局空间,在那里定义了函数,而不是在它被调用的地方。你知道吗</p>
<pre><code>def foo():
global y # assumes that y exist in the current module
y = 5 # when you change it's value it change the value of y in the current module
# even that we used `y` in a left side of assignment expression is not added as local variable
print(foo.__code__.co_varnames)
</code></pre>
<p>当您在没有定义变量<code>y</code>的模块中定义<code>foo</code>时,<code>foo</code>将在该模块的全局范围内找不到该变量,这就是为什么会得到:<code>NameError: name 'y' is not defined</code>。你知道吗</p>
<p>要进一步了解role<code>global</code>关键字,请检查以下内容:</p>
<pre><code>def foo():
global y
y = 1 # this set the variable in the scope of module not the scope of this function
print('y' in locals()) # False it's not a local variable of this method
print('y' in globals()) # False
foo()
print('y' in globals()) # True
</code></pre>