我如何得到一个函数的名字作为字符串?
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
其他回答
sys._getframe()并不保证在Python的所有实现中都可用(参见ref),你可以使用traceback模块来做同样的事情,例如。
import traceback
def who_am_i():
stack = traceback.extract_stack()
filename, codeline, funcName, text = stack[-2]
return funcName
调用stack[-1]将返回当前进程的详细信息。
Try
import sys
fn_name = sys._getframe().f_code.co_name
进一步的参考 https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
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__属性,所以你只需要记住一个特殊的名称。
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
你可以通过使用特殊的__name__变量来获取一个字符串形式的函数名。
def my_function():
pass
print(my_function.__name__) # prints "my_function"