python nonlocal 和 global 的区别

https://blog.csdn.net/xcyansun/article/details/79672634

https://blog.csdn.net/qq_40223983/article/details/99315870

 https://segmentfault.com/a/1190000021625267

简单总结:

1)任何一层子函数,若直接使用全局变量且不对其改变的话,则共享全局变量的值;一旦子函数中改变该同名变量,则其降为该子函数所属的局部变量;

2)global可以用于任何地方,声明变量为全局变量(声明时,不能同时赋值);声明后再修改,则修改了全局变量的值;

3)而nonlocal的作用范围仅对于所在子函数的上一层函数中拥有的局部变量,必须在上层函数中已经定义过,且非全局变量,否则报错。

 

nonlocal

只在闭包里面生效,作用域就是闭包里面的,外函数和内函数都影响,但是闭包外面不影响。

nonlocal 语句使列出的标识符引用除global变量外最近的封闭范围中的以前绑定的变量。 这很重要,因为绑定的默认行为是首先搜索本地名称空间。 该语句允许封装的代码将变量重新绑定到除全局(模块)作用域之外的本地作用域之外。

 

举例

没有用 nonlocal 和 global

x = 0
def 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 = 0
def 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

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

 

 

# E
x = 'Global'
def func3():
x = 'Enclosing'
def func2():
return x
return func2

var = func3()
print( var() )

输出:Enclosing


posted @ 2021-04-16 14:27  milkty  阅读(3199)  评论(0编辑  收藏  举报