获取当前运行函数和方法的名字

# -*- coding: utf-8 -*-
# @Time    : 2018/9/11 10:18
# @Author  : cxa
# @File    : tool.py
# @Software: PyCharm
import sys
from functools import wraps
import inspect
def get_method_name():
    return inspect.stack()[1][3]
def timeit(func):
    @wraps(func)
    def run(*args):
        print("获取当前方法名方式1",func.__name__)
        if args:
            ret=func(*args)
        else:
            ret=func()
        return ret
    return run

@timeit
def ao():
    #print(ao.__name__)#获取方法名
    #print(getattr(ao,'__name__'))
    print("获取当前方法名方式2",sys._getframe().f_code.co_name)
    print("获取当前方法名方式3",get_method_name())


class A():
    def __init__(self):
        pass
    @timeit
    def get(self):
        print("获取当前方法名方式2", sys._getframe().f_code.co_name)
        print("获取当前方法名方式3", get_method_name())
        pass
if __name__ == '__main__':
     ao()
     A().get()

  

原文地址:https://www.cnblogs.com/c-x-a/p/9626079.html