mgi*_*son 59
python中的每个"变量"都限于某个范围.python"file"的范围是模块范围.考虑以下:
#file test.py
myvariable = 5 # myvariable has module-level scope
def func():
x = 3 # x has "local" or function level scope.
Run Code Online (Sandbox Code Playgroud)
具有局部作用域的对象在函数退出后立即死亡,并且永远无法检索(除非您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()
Run Code Online (Sandbox Code Playgroud)
但是,您不能在该引用上使用赋值,并期望它将传播到外部作用域:
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
Run Code Online (Sandbox Code Playgroud)
现在,我们终于到了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
Run Code Online (Sandbox Code Playgroud)
换句话说,如果使用关键字,则可以myvariable从内部更改模块范围中的值.funcglobal
另外,范围可以任意嵌套:
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()
Run Code Online (Sandbox Code Playgroud)
现在在这种情况下,没有变量在全局范围内声明,而在python2中,没有(简单/干净)方法来改变x范围func1内的值func3.这就是nonlocalpython3.x中引入关键字的原因. nonlocal是一个扩展,global它允许您修改从另一个范围中提取的变量,无论它从哪个范围中提取.
| 归档时间: |
|
| 查看次数: |
32512 次 |
| 最近记录: |