[英]Get name of outer function from inner function object in python
Assume a nested function in python, where outer
denotes the outer function and inner
denotes the inner function. 假设python中有嵌套函数,其中outer
表示外部函数, inner
表示内部函数。 The outer function provides parametrization of the inner function and returns an instance of this parametrized function. 外部函数提供内部函数的参数化,并返回此参数化函数的实例。
I want to obtain the name of the outer function, given an instance of the inner function which is returned by the outer function. 我想获得外部函数的名称,给出一个由外部函数返回的内部函数的实例。 The code is as follows: 代码如下:
def outer(a):
def inner(x):
return x*a
return inner
p = outer(3)
print p # prints inner
print p(3) # prints 9
How can I print the name of the outer function, ie outer
, given only p
? 如何打印外部函数的名称,即outer
,只给出p
? Thanks! 谢谢!
You can use functools.wraps
: 你可以使用functools.wraps
:
from functools import wraps
def outer(a):
@wraps(outer)
def inner(x):
return x*a
return inner
p = outer(3)
print p # <function outer at ...>
This is by no means an elegant solution, and I personally wouldn't use it. 这绝不是一个优雅的解决方案,我个人不会使用它。 However it answers the question that you asked. 但它回答了你问的问题。
def outer(a):
def inner(x):
return x*a
inner.__name__ = 'outer'
return inner
print p
<function outer at 0x10eef8e60>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.