如何获取嵌套的函数对象

2024-04-26 09:30:07 发布

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

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\u代码.co\u常数。但是我还没有找到一种方法来获取嵌套函数的函数对象。你知道吗

感谢您的帮助。你知道吗


Tags: 对象函数ingetfoodeffunctionsam
1条回答
网友
1楼 · 发布于 2024-04-26 09:30:07

正如您所注意到的,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

相关问题 更多 >