Pythonnonlocal与global关键字解析说明
来源:动视网
责编:小采
时间:2020-11-27 14:25:44
Pythonnonlocal与global关键字解析说明
Pythonnonlocal与global关键字解析说明:nonlocal首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print
导读Pythonnonlocal与global关键字解析说明:nonlocal首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print

global
还是一样,看一个例子:
x = 0
def outer():
x = 1
def inner():
global x
x = 2
print("inner:", x)
inner()
print("outer:", x)
outer()
print("global:", x)
结果
# inner: 2
# outer: 1
# global: 2
global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。
Pythonnonlocal与global关键字解析说明
Pythonnonlocal与global关键字解析说明:nonlocal首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print