深入理解Python闭包概念(4)

local variable
          0 LOAD_DEREF              0 (loc_var)         # 将cell对象中的slot 0对象的引用压入栈顶
RETURN_VALUE                         # Returns with TOS to the caller of the function

这个结果中,我们反汇编了外层函数及其返回的闭包函数(为了便于查看,修改了部分行号)。从对上面两个函数的反汇编的注释可以大致了解闭包实现的步骤。

python闭包中引用的自由变量实际存放在一个Cell对象中,当自由变元被闭包引用时,便将Cell中存放的自由变量的引用放入栈顶。

本例中Cell对象及其存放的自由变量分别为:

clo_func.func_closure[0] #Cell Object clo_func.func_closure[0].cell_contents == 'local variable' # Free Variable

闭包实现的一个关键的地方是Cell Object,下面是官方给出的解释:

“Cell” objects are used to implement variables referenced by multiple scopes. For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of the cell object requires support from the generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere.

好了,限于篇幅就先介绍到这里。重要的是理解的基础上灵活的应用解决实际的问题并避免陷阱,希望本文能让你对闭包有一个不一样的认识。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0f37c84842a32880f62bf807825c52d1.html