我有这个密码:
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
?你知道吗
你可以作弊并这样做:
但是,如果函数更复杂(自由变量比
fn
多),则必须将其与callers[0].func_code.co_freevars
联系起来。另外,像这样直接摆弄闭包对象也是一件可疑的事情。最终,inner
会丢弃有关它包装的函数名称的信息;您只能通过这种欺骗方式将其取回。如果make_caller
希望其他人能够知道包装函数的名称,那么它应该显式地提供这些信息。你知道吗可以使用\uuuu closure\uuu属性访问它们:
\uu closure\uem>属性记录在https://docs.python.org/2.7/reference/datamodel.html?highlight=closure#the-standard-type-hierarchy的可调用类型部分中
相关问题 更多 >
编程相关推荐