Python中函数的嵌套及闭包

函数的嵌套

调用:在函数中调用函数

定义:在函数中定义函数

地址:函数名有内存地址,内存地址可赋值

示例

a = 1
def outer():
    a = 1
    def inner():
        a = 2
        def inner2():
            nonlocal a
            a += 1
        inner2()
        print('##a## : ', a)
    inner()
    print('**a** : ',a)

OUTER = outer
OUTER()
print('全局 :',a)

nonlocal:声明了一个上层局部变量(寻找上层最近的局部变量)用于局部变量中不可变数据类型的修改;仅在python3中有用

函数的闭包

  • 闭包一定是嵌套函数
  • 闭包一定是内部函数调用外部函数
  • 主要功能是用来节省函数中的部分内存地址

示例:__closure__

def outer():
    a = 1
    def inner():
        print(a)
    print(inner.__closure__)
outer()

__closure__处理方法之后,有cell关键字则该函数就是一个闭包

示例:在外部调用闭包的场景方式

def outer():
    a = 1
    def inner():
        print(a)
    return inner
inn = outer()
inn()

示例

from urllib.request import urlopen
def get_url():
    url = 'https://www.baidu.com'
    def get():
        ret = urlopen(url).read()
        print(ret)
    return get

get_func = get_url()
get_func()
原文地址:https://www.cnblogs.com/guge-94/p/10436010.html