在函数本身中打印函数名称

时间:2018-04-18 14:27:34

标签: python function

我有很多功能,如:

def DBworker_thatdoes_job7():
    print "DBworker_thatdoes_job7 starting..."

    ... the actual code here ...

    print "DBworker_thatdoes_job7 finished."

如何在不对函数名称进行硬编码的情况下执行此操作?这就是我想要实现的目标:

def DBworker_thatdoes_job7():
    print thisfunction.name + " starting..."
    ...

def DBworker_thatdoes_cleaning18():
    print thisfunction.name + " starting..."
    ...

注意:我已经看过How to get a function name as a string in Python?,但我真的没有在这里看到一个很好的方法。此外,这个问题接近于Determine function name from within that function (without using traceback),但此处适用于启动和结束时函数名称日志记录的特定用例,因此不完全重复。

3 个答案:

答案 0 :(得分:4)

你可以使用装饰者:

def start_finish(f):
    def new_f(*args, **kwargs):
        print("starting", f.__name__)
        f(*args, **kwargs)
        print("finished", f.__name__)
    return new_f

@start_finish
def function():
    print('function body')

function()

打印:

starting function
function body
finished function

答案 1 :(得分:2)

也许是装饰师?

def log_function_start(fn):
    def wrapper(*args, **kwargs):
        print '{} starting...'.format(fn.__name__)
        fn(*args, **kwargs)
    return wrapper

@log_function_start
def DBworker_thatdoes_job7():
    ...

答案 2 :(得分:0)

如果您手动实现可调用,即通过使用__call__方法创建类,您可以有更多余地来自定义函数。

>>> class foo(object): # or class foo: in Python 3
...     def __call__(self):
...         # your logic goes here
...         print(type(self).__name__)
... 
>>> foo = foo()
>>> foo()
foo