我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
我如何得到一个函数的名字作为字符串?
def foo():
pass
>>> name_of(foo)
"foo"
当前回答
你可以通过使用特殊的__name__变量来获取一个字符串形式的函数名。
def my_function():
pass
print(my_function.__name__) # prints "my_function"
其他回答
my_function.func_name
函数还有其他有趣的属性。输入dir(func_name)来列出它们。func_name.func_code。Co_code是编译后的函数,存储为字符串。
import dis
dis.dis(my_function)
将以几乎人类可读的格式显示代码。:)
import inspect
def foo():
print(inspect.stack()[0][3])
在哪里
Stack()[0]是调用者 [3]是方法的字符串名称
如果你对类方法也感兴趣,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"
你可以通过使用特殊的__name__变量来获取一个字符串形式的函数名。
def my_function():
pass
print(my_function.__name__) # prints "my_function"
该函数将返回调用方的函数名。
def func_name():
import traceback
return traceback.extract_stack(None, 2)[0][2]
这就像Albert Vonpupp用友好的包装给出的答案。