什么是 全球声明 ?以及如何使用?我已经阅读了Python的官方定义; 但是,这对我来说没有多大意义。
python中的每个“变量”都限于特定范围。python“文件”的范围是模块范围。考虑以下:
#file test.py myvariable = 5 # myvariable has module-level scope def func(): x = 3 # x has "local" or function level scope.
具有局部作用域的对象会在函数退出后立即死亡,并且永远无法检索(除非您拥有return它们),但是在函数内,您可以访问模块级作用域(或任何包含的作用域)中的变量:
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关键字是你告诉蟒蛇,在你的函数特定变量是在全局(模块级)范围定义方式。
global
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
换句话说,如果您使用关键字,则可以myvariable从内部更改module-scope中的值。func``global
myvariable
func``global
顺便说一句,合并范围可以任意深度嵌套:
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,不存在(易/干净)的方式来改变的值x在范围func1从内func3。这就是为什么nonlocal在python3.x中引入了关键字的原因。 nonlocal的扩展,global它允许您修改从其他作用域中提取的变量,而不论该变量是从哪个作用域中提取的。
x
func1
func3
nonlocal