闭包中内函数如何修改外函数中局部变量的值

 

1、

>>> def a():
    x = 10
    def b():
        x = x + 8
        print(x)
    return b

>>> a()
<function a.<locals>.b at 0x000001B47F4D8040>
>>> a()()
Traceback (most recent call last):
  File "<pyshell#649>", line 1, in <module>
    a()()
  File "<pyshell#647>", line 4, in b
    x = x + 8
UnboundLocalError: local variable 'x' referenced before assignment

python认为在内部函数的x是局部变量的时候,外部函数的x就被屏蔽了起来,所以在执行 x = x + 8的时候找不到x的值,因此报错。

>>> def a():
    x = [100]
    def b():
        x[0] = x[0] + 8
        print(x[0])
    return b

>>> a()()
108
>>> c = a()
>>> c()
108

 

>>> def a():
    x = 100
    def b():
        nonlocal x
        x = x + 8
        print(x)
    return b

>>> a()
<function a.<locals>.b at 0x000001DA3D2EA040>
>>> a()()
108
>>> c = a()
>>> c()
108

 

 2、

>>> def a():
    x = 10
    def b():
        nonlocal x
        x = x + 8
        print(x)
    return b

>>> c = a()
>>> c()
18
>>> c()
26
>>> c()
34
>>> for i in range(5):
    c()

    
42
50
58
66
74

 

闭包概念的引入是为了尽可能地避免使用全局变量,闭包允许将函数与其所操作的某些数据(环境)关联起来,这样外部函数就为内部函数构成了一个封闭的环境。

 

参考:https://www.cnblogs.com/s-1314-521/p/9763376.html

 

posted @ 2021-03-05 22:27  小鲨鱼2018  阅读(474)  评论(0编辑  收藏  举报