如何以字符串形式获取函数名称? [英] How to get a function name as a string?

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

问题描述

在 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 不同,它也适用于内置函数:

<预><代码>>>>导入时间>>>time.time.func_name回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 ?AttributeError: 'builtin_function_or_method' 对象没有属性 '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屋!

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