zoukankan      html  css  js  c++  java
  • pyton中函数的闭包

    什么是闭包?

    1、内层函数对外层函数(非全局)变量的引用

    2、闭包只存在于内层函数中

    3、闭包要逐层返回,最终返回给最外层函数

    # 不是闭包
    name = 'rock'
    
    def func():
        def inner():
            print(name)
        return inner
    
    
    f = func()
    print(f.__closure__[0].cell_contents) # 查看是报错 
    # 是闭包
    def func():
        name = 'rock'
        age = 23
    
        def inner():
            print(name)
            print(age)
        return inner
    
    
    ret1 = func()
    print(ret1.__closure__[0].cell_contents)    # 20 从内到外
    print(ret1.__closure__[1].cell_contents)    # rock

    闭包函数的特点:

    解释器执行程序时如果遇到闭包,有一个机制:就是闭包的空间不会随着函数调用的结束而关闭,

    闭包会在内存中开辟的空间,常贮存一些内容以便后续程序调用。若解释器遇到的函数不是闭包,则调用之后空间释放

    # 非闭包
    def func1(step):
        num = 1
        num += step
        print(num)  # 4 4 4 4 4
    
    
    j = 0
    while j < 5:
        func1(3)
        j += 1
    print('*' * 30)
    
    
    # 闭包
    def func2(step):
        num = 1
    
        def inner():
            nonlocal num
            num += step
            print(num)  # 4 7 10 13 16
        return inner
    
    
    f = func2(3)
    n = 0
    while n < 5:
        # func2(3)()    # 这个相当每次执行func2后再执行inner,每次都重新释放临时空间再开辟临时临时空间,每次开辟了五个闭包
        f()     # 单独调用inner,pyhton识别是闭包,空间会保存一段时间
        n += 1

    闭包的应用:

    1、装饰器

    2、爬虫

  • 相关阅读:
    《最优化导论》-8梯度方法
    《最优化导论》-7一维搜索方法
    《最优化导论》-6集合约束和无约束优化问题基础
    ubuntu set up 3
    ubuntu set up 2
    ubuntu set up 1
    Xavier and Kaiming Initialization
    Network Initialization: Fan-in and Fan-out
    The Softmax function and its derivative
    GNU Screen使用
  • 原文地址:https://www.cnblogs.com/chen55555/p/10209247.html
Copyright © 2011-2022 走看看