从返回的函数中访问引用的闭包值

2024-06-28 21:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个了结

def create_f():
   a = 5
   def _inner(x):
      return a * x
   return _inner
f = create_f()

嵌套函数f引用封闭函数中定义的值a。是否可以仅通过f访问a的值,例如:

get_deref_value_magic('a', f) # should be 5

我之所以需要它,是因为我正在编写一个模块,该模块使用dis反汇编函数,从中创建OpenCL/Cuda代码。在这个场景中,我坚持使用以下指令,因为我不知道如何访问值a

Instruction(opname='LOAD_DEREF', opcode=136, arg=0, argval='a', argrepr='a', offset=0, starts_line=22, is_jump_target=False)

(如何)我可以访问a(即5)的实际值


Tags: 模块函数getreturn定义valuedefcreate