python中函数的闭包

 

1、

>>> def a(x):
    def b(y):
        return x * y
    return b

>>> temp = a(5)    ## 内嵌函数调用外部函数的变量
>>> temp(8)
40

 

2、

>>> def a():
    x = 5
    def b():
        x = x + 1       ## x在内部函数是局部变量,只能访问外层函数的变量,无法修改??
        return x
    return b

>>> temp = a()
>>> temp()
Traceback (most recent call last):
  File "<pyshell#803>", line 1, in <module>
    temp()
  File "<pyshell#801>", line 4, in b
    x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

 

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

>>> temp = a()
>>> temp
<function a.<locals>.b at 0x00000143F5C78040>
>>> temp()
110

 

>>> def a():
    x = 100
    def b():
        nonlocal x     ## 因素nonlocal关键字
        x = x + 10
        return x
    return b

>>> temp = a()
>>> temp()
110

 

posted @ 2021-03-04 17:34  小鲨鱼2018  阅读(52)  评论(0编辑  收藏  举报