可能重复:
How do I get the name of a function or method from within a Python function or method?在函数中引用函数的__name__的最佳方法是什么?
下面的代码的函数返回它的名字。 它有效,但我仍然必须指定'测试'。在__name__
的前面。 有没有一般的方法可以参考__name__
?
def test():
print test.__name__
可能重复:
How do I get the name of a function or method from within a Python function or method?在函数中引用函数的__name__的最佳方法是什么?
下面的代码的函数返回它的名字。 它有效,但我仍然必须指定'测试'。在__name__
的前面。 有没有一般的方法可以参考__name__
?
def test():
print test.__name__
没有办法在不使用回溯的情况下访问python函数中的函数名称。
In [1]: import inspect
In [2]: def test():
...: print inspect.stack()[0][3]
...:
In [3]: test()
test
所以,你想用的是inspect.stack()[0][3]
或者,如果你想将其移动到一个单独的功能,inspect.stack()[1][3]
(从How do I get the name of a function or method from within a Python function or method?)
如果我理解正确的话 - Inspect是什么你正在寻找。
import inspect
def test():
print inspect.stack()[0][3]
我不明白。 – motoku 2011-06-09 07:55:52