python中的每个“变量”都被限制在一定的范围内。python“文件”的作用域是模块作用域。请考虑以下几点:#file test.py
myvariable = 5 # myvariable has module-level scope
def func():
x = 3 # x has "local" or function level scope.
具有本地作用域的对象在函数退出时即消失,并且永远无法检索(除非您return它们),但是在函数中,您可以访问模块级作用域(或任何包含作用域)中的变量:myvariable = 5
def func():
print(myvariable) # prints 5
def func2():
x = 3
def func3():
print(x) # will print 3 because it picks it up from `func2`'s scope
func3()
但是,不能对该引用使用赋值,并期望它将传播到外部作用域:myvariable = 5
def func():
myvariable = 6 # creates a new "local" variable.
# Doesn't affect the global version
print(myvariable) # prints 6
func()
print(myvariable) # prints 5
现在,我们终于要global。关键字global是告诉python函数中的特定变量是在全局(模块级)范围内定义的。myvariable = 5
def func():
global myvariable
myvariable = 6 # changes `myvariable` at the global scope
print(myvariable) # prints 6
func()
print(myvariable) # prints 6 now because we were able
# to modify the reference in the function
换句话说,如果使用global关键字,则可以从func内更改模块作用域中myvariable的值。
另外,作用域可以任意深度嵌套:def func1():
x = 3
def func2():
print("x=",x,"func2")
y = 4
def func3():
nonlocal x # try it with nonlocal commented out as well. See the difference.
print("x=",x,"func3")
print("y=",y,"func3")
z = 5
print("z=",z,"func3")
x = 10
func3()
func2()
print("x=",x,"func1")
func1()
在本例中,没有一个变量是在全局范围内声明的,在python2中,没有(简单/干净的)方法可以从func3内更改x范围内的func1的值。这就是python3.x中引入nonlocal关键字的原因。nonlocal是global的一个扩展,它允许您修改从另一个作用域中提取的变量,无论该变量是从哪个作用域提取的。