python闭包实现
1.python 闭包是函数变量的不同保存形式
如下python将d 作为函数的普通变量保存在locals 中
def g(): d = {} def f(): #d["a"] = 1 pass return f code = g.__code__ print(f"nlocals: {code.co_nlocals}") print(f"varnames: {code.co_varnames}") print(f"names: {code.co_names}") print(f"cellvars: {code.co_cellvars}") print(f"freevars: {code.co_freevars}") print(f"consts: {code.co_consts}")
nlocals: 2 varnames: ('d', 'f') names: () cellvars: () freevars: () consts: (None, <code object f at 0x00000228B5B9F360, file "xx.py", line 3>)
而当将 d 在 f 中使用,成为闭包中的变量时,编译器会将 d 放到 cellvars 中
当查看g() 的bytecode时,可以看到 d 保存在了g() 对象的 freevars 中
当使用dis 模块反汇编python 字节码时也可以看到,在python闭包中使用的字节码与正常函数调用不同
当变量在闭包中时,使用 STORE_DEREF
当变量不在闭包中时,使用 STORE_FAST
而闭包的查找顺序为:https://www.cnblogs.com/shiqi17/p/9331002.html
人生还有意义。那一定是还在找存在的理由