python中的每个“变量”都限于某个范围. python“文件”的范围是模块范围.考虑以下:
#file test.py
myvariable = 5 # myvariable has module-level scope
def func():
x = 3 # x has "local" or function level scope.
具有局部作用域的对象在函数退出后立即死亡,并且永远无法检索(除非您返回它们),但在函数内,您可以访问模块级作用域(或任何包含作用域)中的变量:
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关键字是告诉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中更改func1范围内的x值.这就是python3.x中引入nonlocal关键字的原因. nonlocal是global的扩展,允许您修改从另一个范围中提取的变量,无论其范围是什么.