小编akm*_*akm的帖子

python 闭包是如何实现的?

我对python如何实现闭包感兴趣?

为了举例,请考虑这个

def closure_test():
    x = 1
    def closure():
        nonlocal x
        x = 2
        print(x)
    return closure

closure_test()()
Run Code Online (Sandbox Code Playgroud)

这里,该函数closure_test有一个x嵌套函数closure捕获的局部变量。

当我运行该程序时,我得到以下输出

2
Run Code Online (Sandbox Code Playgroud)

当我看到函数的反汇编时closure_test

  2           0 LOAD_CONST               1 (1)
              2 STORE_DEREF              0 (x)

  3           4 LOAD_CLOSURE             0 (x)
              6 BUILD_TUPLE              1
              8 LOAD_CONST               2 (<code object closure at 0x7f14ac3b9500, file "<string>", line 3>)
             10 LOAD_CONST               3 ('closure_test.<locals>.closure')
             12 MAKE_FUNCTION            8 (closure)
             14 STORE_FAST               0 (closure)

  7          16 LOAD_FAST                0 (closure)
             18 RETURN_VALUE

Disassembly of …
Run Code Online (Sandbox Code Playgroud)

python closures

6
推荐指数
1
解决办法
563
查看次数

标签 统计

closures ×1

python ×1