Python闭包

闭包的定义

定义

在一个外函数中定义了一个内函数,内函数里运用了外函数的临时变量,并且外函数的返回值是内函数的引用。这样就构成了一个闭包。

python语言中形成闭包的三个条件,缺一不可:

  • a. 必须有一个内嵌函数(函数里定义的函数)——这对应函数之间的嵌套
  • b. 内嵌函数必须引用一个定义在闭合范围内(外部函数里)的变量——内部函数引用外部变量
  • c. 外部函数必须返回内嵌函数——必须返回那个内部函数

闭包的案例

def outer(a):
    b = 10

    def inner():
        print(a+b)

    return inner

if __name__ == '__main__':
    demo = outer(5)
    print(demo)
    demo()

    demo2 = outer(7)
    print(demo2)
    demo2()
    
# <function outer.<locals>.inner at 0x7f454784fea0>
# 15
# <function outer.<locals>.inner at 0x7f454784fe18>
# 17

image

原文地址:https://www.cnblogs.com/Tcorner/p/9115903.html