python 获取函数名字的办法

本博客转自 https://www.zybuluo.com/spiritnotes/note/306113

在程序处理中,有时候需要出现获取函数名字,这时有可能在函数内部,也有可能在函数外部,不同的情况下应该如何获取呢?

函数外部

在函数外部比较简单,直接采用__name__即可

def fun_name():
    pass
z = fun_name
print(z.__name__)
print(getattr(z,'__name__'))

函数内部

而在函数内部就需要复杂一点了,有如下方法:

通过sys._getframe().f_code.co_name获取

 
def fun_name():
    import sys
    print(sys._getframe().f_code.co_name)
z = fun_name
z()

通过装饰器将名字作为参数传入函数

 
def dec_name(f):
    name = f.__name__
    def new_f(*a, **ka):
        return f(*a, __name__ = name, **ka)
    return new_f
@dec_name
def fun_name(x, __name__):
    print(__name__)
z = fun_name
z(1)

通过inspect获取名字

 
import inspect
def fun_name():
    print(inspect.stack()[0][3])
z = fun_name
z()

测试

代码: https://github.com/spiritwiki/codes/tree/master/LearnPython

函数外边获得函数的名字
fun_name
fun_name
函数内部通过sys._getframe().f_code.co_name获得名字
fun_name
通过装饰器将名字作为参数传入函数
fun_name
通过inspect获取名字
fun_name

猜你喜欢

转载自blog.csdn.net/qq_16069927/article/details/89043169
今日推荐