如何以字符串形式获取函数名称? [英] How to get a function name as a string?
问题描述
在 Python 中,如何在不调用函数的情况下以字符串形式获取函数名称?
def my_function():经过print get_function_name_as_string(my_function) # my_function 不在引号中
应该输出"my_function"
.
这样的函数在 Python 中可用吗?如果没有,关于如何在 Python 中实现 get_function_name_as_string
的任何想法?
my_function.__name__
使用 __name__
是首选方法,因为它统一适用.与 func_name
不同,它也适用于内置函数:
双下划线也向读者表明这是一个特殊的属性.作为奖励,类和模块也有一个 __name__
属性,所以你只需要记住一个特殊的名称.
In Python, how do I get a function name as a string, without calling the function?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
should output "my_function"
.
Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string
, in Python?
my_function.__name__
Using __name__
is the preferred method as it applies uniformly. Unlike func_name
, it works on built-in functions as well:
>>> 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'
Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__
attribute too, so you only have remember one special name.
这篇关于如何以字符串形式获取函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!