如何在Python中获取函数名称作为字符串? [英] How to get a function name as a string in Python?

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

问题描述

在Python中,如何在不调用函数的情况下将函数名称作为字符串?

  def my_function(): 
传递

print get_function_name_as_string(my_function)#my_function不在引号中

应输出my_function



这是否可用于python?如果没有,请问如何在Python中编写 get_function_name_as_string

$ p $ my_function .__ name__

使用 __ name __ 是首选方法,因为它一律适用。与 func_name 不同,它也适用于内置函数:

  >>>进口时间
>>> time.time.func_name
Traceback(最近一次调用最后一次):
文件< stdin>,第1行,in?
AttributeError:'builtin_function_or_method'对象没有属性'func_name'
>>> time.time .__ name__
'time'

同样,双下划线表示读者是一个特殊的属性。作为奖励,类和模块也有一个 __ 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 this available in python? If not, any idea how to write 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.

这篇关于如何在Python中获取函数名称作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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