访问函数的内部函数

crk*_*crk 4 python python-2.7

def myFunc( a, b ):
  def innerFunc( c ):
    print c
  innerFunc( 2 )
  print a, b
Run Code Online (Sandbox Code Playgroud)

如何直接访问内部函数?我想要格式化该函数的对象/地址

<function innerFunc at 0xa0d5fb4>
Run Code Online (Sandbox Code Playgroud)

我尝试使用myFunc._ getattr _('innerFunc'),但这不起作用.

JBe*_*rdo 5

由于函数在函数调用之前不存在(并且仅在函数调用期间存在),因此无法访问它.

如果闭包不重要,可以直接从放在外部函数内的代码常量构建内部函数:

inner = types.FunctionType(myFunc.__code__.co_consts[1], globals())
Run Code Online (Sandbox Code Playgroud)

函数const值内的位置可能会有所不同......

此解决方案不需要调用myFunc.