在 Python 中,如何在不调用函数的情况下以字符串形式获取函数名称?
def my_function():
    pass
print get_function_name_as_string(my_function) # my_function is not in quotes应该输出"my_function" 。
此类功能在 Python 中可用吗?如果没有,关于如何在 Python 中get_function_name_as_string
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
this_function_name = inspect.currentframe().f_code.co_namesys._getframe也可以代替inspect.currentframe尽管后者避免访问私有函数。
要获取调用函数的名称,请考虑将f_back视为inspect.currentframe().f_back.f_code.co_name 。
如果还使用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.func_name函数还有其他有趣的属性。键入dir(func_name)列出它们。 func_name.func_code.co_code是已编译的函数,存储为字符串。
import dis
dis.dis(my_function)将以几乎人类可读的格式显示代码。 :)