Python闭包closure

闭包(closure)是函数式编程中一个非常重要的概念。

从字面上理解,就是内嵌函数将外层函数的变量“包”进来,并且“固定”不变,从而形成一个函数。所以一个高阶函数外层输入不同的自变量时,可以创建不同的闭包函数。

def high_order_func(i):
    def enclosing_func(a):
        return a + i

    return enclosing_func


hfunc1 = high_order_func(20)    # 创建闭包函数
print(hfunc1(10))
print(hfunc1(20))               # 变量i仍然固定在闭包函数内,没有失效
print(hfunc1.__closure__)

hfunc2 = high_order_func(50)
print(hfunc2(10))
print(hfunc2.__closure__[0].cell_contents)

输出:
30
40
(<cell at 0x0000010F9A42B4C8: int object at 0x0000000071CA6300>,)
60
50

猜你喜欢

转载自blog.csdn.net/slx_share/article/details/80374628