我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
当前回答
import inspect
def my_first_function():
func_name = inspect.stack()[0][3]
print(func_name) # my_first_function
or:
import sys
def my_second_function():
func_name = sys._getframe().f_code.co_name
print(func_name) # my_second_function
其他回答
Try
import sys
fn_name = sys._getframe().f_code.co_name
进一步的参考 https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
要从函数或方法中获取当前函数或方法的名称,考虑:
import inspect
this_function_name = inspect.currentframe().f_code.co_name
sys。_getframe也可以代替inspect。虽然后者避免访问私有函数。
要获得调用函数的名称,请考虑inspect.currentframe().f_back.f_code.co_name中的f_back。
如果也使用mypy,它可以抱怨:
选项"Optional[FrameType]"中的"None"没有属性"f_code"
为了抑制上述错误,考虑:
import inspect
import types
from typing import cast
this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name
my_function.__name__
使用__name__是首选方法,因为它是统一应用的。与func_name不同,它也适用于内置函数:
>>> import time
>>> time.time.func_name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__
'time'
此外,双下划线向读者表明这是一个特殊属性。作为奖励,类和模块也有__name__属性,所以你只需要记住一个特殊的名称。
你只需要知道函数的名字这是一个简单的代码。 假设你已经定义了这些函数
def function1():
print "function1"
def function2():
print "function2"
def function3():
print "function3"
print function1.__name__
输出将是function1
现在假设你有一个列表中的这些函数
a = [function1 , function2 , funciton3]
来获取函数的名称
for i in a:
print i.__name__
输出将是
function1 function2 function3
import inspect
def my_first_function():
func_name = inspect.stack()[0][3]
print(func_name) # my_first_function
or:
import sys
def my_second_function():
func_name = sys._getframe().f_code.co_name
print(func_name) # my_second_function