简体   繁体   English

从python中的内部函数对象获取外部函数的名称

[英]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.

相关问题 在没有外部函数交互的情况下获取内部函数结果 - Get inner function result without interaction of outer function in python 在Python中,是否可以使用内部函数体内的外部函数变量? - Is there a way to use variable from outer function in the inner function body, in Python? Maya Python:从内部函数访问外部函数变量 - Maya Python: Accessing outer function variable from inner function 在python中将相同的参数从外部函数传递给内部函数 - passing same argument from outer function to inner function in python 在 Python 中将多个关键字参数从外部函数传递到内部函数? - relay multiple keyword arguments from outer function to inner functions in Python? 从内部函数访问外部函数的变量 - Access variable of outer function from inner function 如何从外部函数获取参数? Python - how to get an argument from an outer function? python 如何在外部函数中定义内部函数的参数名称? - How can I define the argument name of an inner function in an outer function? 在Python中将内部函数的返回值传递给外部函数? - Passing the returned value of the inner function to the outer function in Python? Python内部函数不打印外部函数中初始化的值 - Python inner function not printing the value that was initialised in the outer function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM