2011-08-22 124 views
3

可能重複:
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?獲取函數名稱作爲Python中的字符串

我有一個名爲FUNC功能,我希望能夠得到函數名稱爲一個字符串。

僞蟒蛇:

def func() : 
    pass 

print name(func) 

這將打印 '功能'。

+2

想知道的名字功能常常是設計不理想的標誌。爲什麼你想知道它的定義名稱?你將如何使用它?你知道一個函數是一個對象,可以像Python中的任何其他值一樣對待嗎? –

+0

在大多數情況下,我會同意你的看法。然而,在我的特殊情況下,我正在製作一個工具,可以打印出有關任意函數的某些信息。我想在打印輸出中使用該功能的名稱。它沒有任何形式的結構性位置。 – rectangletangle

+0

這並不總是壞事。例如,unittest使用函數的名字來檢測哪些應該運行。 – dbn

回答

17

這很簡單。

print func.__name__ 

編輯:但是你一定要小心:

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

另外,一個方便的提示:像你這樣的簡單問題可以很容易地通過使用'dir'內置函數來回答。例如'dir(func)'返回一個列表,其中'__name __'作爲其中一項。 – Umang

+0

對評論的回答爲+1 – eyquem

2

使用__name__

例子:

def foobar(): 
    pass 

bar = foobar 

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

有關與Python自省的概述看看http://docs.python.org/library/inspect.html

1

一對夫婦更多的方式來做到這一點:

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