如何在Python中获得嵌套函数的名称空间?

2024-06-10 12:49:56 发布

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

我有这个密码:

def make_caller(fn):
    def inner():
        fn()
    return inner

def random_function_1(): pass
def random_function_2(): return 42
def random_function_3(): return 69

callers = [
    make_caller(random_function_1),
    make_caller(random_function_2),
    make_caller(random_function_3),
]

现在callers中的所有函数都被称为inner

>>> [x.__name__ for x in callers]
['inner', 'inner', 'inner']

使用callers,如何获得random_function_1random_function_2random_function_3?你知道吗


Tags: 函数namein密码formakereturndef
2条回答

你可以作弊并这样做:

>>> callers[0].func_closure[0].cell_contents.__name__
'random_function_1'

但是,如果函数更复杂(自由变量比fn多),则必须将其与callers[0].func_code.co_freevars联系起来。另外,像这样直接摆弄闭包对象也是一件可疑的事情。最终,inner会丢弃有关它包装的函数名称的信息;您只能通过这种欺骗方式将其取回。如果make_caller希望其他人能够知道包装函数的名称,那么它应该显式地提供这些信息。你知道吗

Using callers, how can I get random_function_1, random_function_2, and random_function_3?

可以使用\uuuu closure\uuu属性访问它们:

>>> [caller.__closure__[0].cell_contents for caller in callers]
[<function random_function_1 at 0x1004e0de8>, <function random_function_2 at 0x1004e0e60>, <function random_function_3 at 0x103b70de8>]

\uu closure\uem>属性记录在https://docs.python.org/2.7/reference/datamodel.html?highlight=closure#the-standard-type-hierarchy的可调用类型部分中

相关问题 更多 >