我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
当前回答
Try
import sys
fn_name = sys._getframe().f_code.co_name
进一步的参考 https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
其他回答
如果你对类方法也感兴趣,Python 3.3+除了__name__还有__qualname__。
def my_function():
pass
class MyClass(object):
def method(self):
pass
print(my_function.__name__) # gives "my_function"
print(MyClass.method.__name__) # gives "method"
print(my_function.__qualname__) # gives "my_function"
print(MyClass.method.__qualname__) # gives "MyClass.method"
my_function.func_name
函数还有其他有趣的属性。输入dir(func_name)来列出它们。func_name.func_code。Co_code是编译后的函数,存储为字符串。
import dis
dis.dis(my_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
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
该函数将返回调用方的函数名。
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
这就像Albert Vonpupp用友好的包装给出的答案。