PHP前端开发

Python nonlocal与global关键字解析说明

百变鹏仔 3小时前 #Python
文章标签 关键字

nonlocal

首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:

x = 0def outer():    x = 1    def inner():        x = 2        print("inner:", x)    inner()    print("outer:", x)outer()print("global:", x)

结果

# inner: 2# outer: 1# global: 0

现在,在闭包里面加入nonlocal关键字进行声明:

x = 0def outer():    x = 1    def inner():        nonlocal x        x = 2        print("inner:", x)    inner()    print("outer:", x)outer()print("global:", x)

结果

# inner: 2# outer: 2# global: 0
看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面才有效, 而是在整个大函数里面都有效。

global

还是一样,看一个例子:

立即学习“Python免费学习笔记(深入)”;

x = 0def 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 是对整个环境下的变量起作用,而不是对函数类的变量起作用。