python中的每个“变量”都限于特定范围。python“文件”的范围是模块范围。考虑以下:
#file test.pymyvariable = 5 # myvariable has module-level scopedef func(): x = 3 # x has "local" or function level scope.
具有局部作用域的对象会在函数退出后立即死亡,并且永远无法检索(除非您拥有
return它们),但是在函数内,您可以访问模块级作用域(或任何包含的作用域)中的变量:
myvariable = 5def func(): print(myvariable) # prints 5def func2(): x = 3 def func3(): print(x) # will print 3 because it picks it up from `func2`'s scope func3()
但是,您不能在该引用上使用赋值,并且期望它会传播到外部作用域:
myvariable = 5def func(): myvariable = 6 # creates a new "local" variable. # Doesn't affect the global version print(myvariable) # prints 6func()print(myvariable) # prints 5
现在,我们终于可以了
global。该
global关键字是你告诉蟒蛇,在你的函数特定变量是在全局(模块级)范围定义方式。
myvariable = 5def func(): global myvariable myvariable = 6 # changes `myvariable` at the global scope print(myvariable) # prints 6func()print(myvariable) # prints 6 now because we were able # to modify the reference in the function
换句话说,如果您使用关键字,则可以
myvariable从内部更改module-scope中的值。
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它允许您修改从其他作用域中提取的变量,而不论该变量是从哪个作用域中提取的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)