📜  Python|如何获取函数名称?

📅  最后修改于: 2022-05-13 01:55:02.607000             🧑  作者: Mango

Python|如何获取函数名称?

最突出的编码风格之一是遵循 OOP 范式。为此,如今,压力一直是编写具有模块化的代码,以增加调试并创建更健壮、可重用的代码。这一切都鼓励为不同的任务使用不同的函数,因此我们一定会知道某些函数的hack。本文讨论如何打印函数的名称。让我们讨论一些可以做到这一点的方法。

方法 #1:使用function.func_name

通过使用一个简单的函数属性函数 func_name,可以获取函数的名称,因此在测试目的和文档时非常方便。缺点是这只适用于 Python2。

# Python code to demonstrate
# way to get function name
# using function.func_name
  
# initializing function
def GFG():
    return "You just called for success !!"
  
# printing function name 
# using function.func_name
print("The name of function is : " + GFG.func_name)
输出 :
The name of function is : GFG

方法 #2:使用function.__name__

该函数可以作为上述函数的替代,并已在 Python3 中引入,因为上述方法中提到的函数在 Python3 中已被贬值。

# Python code to demonstrate
# way to get function name
# using function.__name__
  
# initializing function
def GFG():
    return "You just called for success !!"
  
# printing function name 
# using function.__name__
print("The name of function is : " + GFG.__name__)
输出 :
The name of function is : GFG