如何为闭包函数创建闭包变量名称的字典值。 Python3.x

时间:2017-07-07 18:24:34

标签: python python-3.x dictionary

使用python模块:

def mult(n):
    a = n-1
    def multn(x):
        b = a
        print (n*x)
    return multn

f = mult(3)
f(4)

print (f.__closure__)
for c in f.__closure__:
    print (c.cell_contents)

print (f.__code__.co_freevars)

输出结果为:

12
(<cell at 0x10fd20360: int object at 0x7f8f9bc0b760>, <cell at 0x10fd20398: int object at 0x7f8f9bc0b748>)
2
3
('a', 'n')

是否有更简单的方式或包存在,它创建了clo_var_nameclo_val的字典?

所以{'a': 2, 'n': 3}

先谢谢大家。

1 个答案:

答案 0 :(得分:1)

inspect.getclosurevars将为您提供闭包引用变量的字典。

<div class="red-square"></div>
<br/>
<button id="btn">
  Hide and Show square
</button>
相关问题