- 函数中使用全局变量
a = 100
b = 200
def func():
def sub():
return b
return a + b + sub()
执行fun()后返回值为:500
a, b使用的是全局变量的值。
- 函数中覆盖全局变量
a = 100
b = 200
def func():
a = 10
b = 20
def sub():
return b
return a + b + sub()
执行fun()后返回值为:50
a, b使用的是局部变量的值。
- 函数中修改改全局变量
a = 100
b = 200
def func():
global a
b = 20
def sub():
nonlocal b
b = 10
sub()
return a + b
执行fun()后返回值为:110
a使用的是全局变量a=100的值, b使用的是函数func修改后b的值10。
- 另一个例子
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
结果:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
- 总结
函数中global关键字用于申明变量为全局变量,在模块中定义的变量默认自动为全局变量。
闭包函数中使用nonlocal关键字申明变量为外层函数的变量。