【问题标题】:How to get the nested function objects?如何获取嵌套的函数对象?
【发布时间】:2013-04-26 08:46:17
【问题描述】:
def foo():
    print "I am foo"
    def bar1():
       print "I am bar1"
    def bar2():
       print "I am bar2"
    def barN():
       print "I am barN"


funobjs_in_foo = get_nest_functions(foo)

def get_nest_functions(funobj):
    #how to write this function??

如何获取所有嵌套的函数对象?我可以通过 funobj.func_code.co_consts 获取嵌套函数的代码对象。但是我还没有找到一种方法来获取嵌套函数的函数对象。

感谢任何帮助。

【问题讨论】:

  • 谢谢。检查框架仅保存代码对象。有人提出了一种使用 gc 从代码对象中获取函数对象的方法。但它不适用于这种嵌套函数场景。

标签: python


【解决方案1】:

如您所见,foo.func_code.co_consts 仅包含代码对象,而不包含函数对象。

您不能仅仅因为它们不存在而获取函数对象。每当调用函数时都会重新创建它们(并且仅重用代码对象)。

确认使用:

>>> def foo():
...     def bar():
...         print 'i am bar'
...     return bar
....
>>> b1 = foo()
>>> b2 = foo()
>>> b1 is b2
False
>>> b1.func_code is b2.func_code
True

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多