Get function name as a string in python [duplicate]

余生长醉 提交于 2019-12-13 13:15:24

问题


Possible Duplicate:
How do I get the name of a function or method from within a Python function or method?
How to get the function name as string in Python?

I have a function named func, I'd like to be able to get the functions name as a string.

pseudo-python :

def func () :
    pass

print name(func)

This would print 'func'.


回答1:


That's simple.

print func.__name__

EDIT: But you must be careful:

>>> def func():
...     pass
... 
>>> new_func = func
>>> print func.__name__
func
>>> print new_func.__name__
func



回答2:


Use __name__.

Example:

def foobar():
    pass

bar = foobar

print foobar.__name__   # prints foobar
print bar.__name__   # still prints foobar

For an overview about introspection with python have a look at http://docs.python.org/library/inspect.html




回答3:


A couple more ways to do it:

>>> def foo(arg):
...     return arg[::-1]
>>> f = foo
>>> f.__name__
'foo'
>>> f.func_name
'foo'
>>> f.func_code.co_name
'foo'


来源:https://stackoverflow.com/questions/7142062/get-function-name-as-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!