可能重複:
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