我有这个密码:
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_1
、random_function_2
和random_function_3
? 最佳答案
使用调用者,如何得到random_函数_1,random_函数_2,
和随机函数?
可以使用“闭包”属性访问它们:
>>> [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>]
https://docs.python.org/2.7/reference/datamodel.html?highlight=closure#the-standard-type-hierarchy的可调用类型部分记录了“闭包”属性
关于python - 如何在Python中获取嵌套函数的 namespace ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24771407/