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

标签 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)但这里适用于在启动和结束时记录函数名称的特定用例,因此不完全重复。

最佳答案

你可以使用装饰器:

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

关于python - 在函数本身中打印函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49902306/

相关文章:

c++ - 函数签名,调用和定义的顺序

c++ - 在第三方函数中使用 vector 引用时出现意外错误

python - 修改脚本: NameError: name '' is not defined

python - 并行运行两个嵌套的 for 循环以创建矩阵

python - 在 Windows 10 上安装 dlib

r - 更有效的方式:selecting vec from a list

带有列表和集合的 Python 函数

python max 函数使用 'key' 和 lambda 表达式

python - cv2.resize() 错误 : saves the same picture with different names

python - 为什么我不能打印在函数内声明的变量?