如何获得一个函数名作为字符串? [英] How to get a function name as a string?

查看:104
本文介绍了如何获得一个函数名作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如何在不调用函数的情况下以字符串形式获取函数名称?

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

应输出"my_function".

这样的函数在Python中可用吗?如果没有,关于如何在Python中实现get_function_name_as_string的任何想法?

Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string, in Python?

推荐答案

my_function.__name__

使用__name__是首选方法,因为它统一适用.与func_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'

此外,双下划线向读者表明这是一个特殊属性.另外,类和模块也具有__name__属性,因此您只记得一个特殊名称.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆