2009-10-08 30 views
8
def applejuice(q): 
    print THE FUNCTION NAME! 

它應該導致「applejuice」作爲字符串。如何在函數內部以Python形式打印函數名稱

+1

見http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question-on-so/25128#25128 – 2009-10-08 20:39:20

+1

從您選擇,我們可以將答案得出結論,這確實是重複的。事實上,一個幾乎完全一樣的問題已經存在:http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python – 2009-10-08 21:45:51

+0

我不同意這是一個#251464的重複 - 看起來這個問題是反過來的。 – 2012-11-10 19:09:08

回答

19

這也適用於:

import sys 

def applejuice(q): 
    func_name = sys._getframe().f_code.co_name 
    print func_name 
2

你需要解釋你的問題是什麼。因爲回答你的問題是:

print "applejuice" 
+2

也許他的意思是:def func(anothah_func):打印anothah_func的名字 – wilhelmtell 2009-10-08 20:27:15

+0

嗯,那絕對有可能。我們會看看他是否說出了問題所在。 – 2009-10-08 20:38:36

7
import traceback 

def applejuice(q): 
    stack = traceback.extract_stack() 
    (filename, line, procname, text) = stack[-1] 
    print procname 

我想這是用於調試,所以你可能想看看traceback module提供的其他程序。他們會告訴你打印整個調用堆棧,異常跟蹤等

3

另一種方式

import inspect 
def applejuice(q): 
    print inspect.getframeinfo(inspect.currentframe())[2] 
0
def foo(): 
    # a func can just make a call to itself and fetch the name 
    funcName = foo.__name__ 
    # print it 
    print 'Internal: {0}'.format(funcName) 
    # return it 
    return funcName 

# you can fetch the name externally 
fooName = foo.__name__ 
print 'The name of {0} as fetched: {0}'.format(fooName) 

# print what name foo returned in this example 
whatIsTheName = foo() 
print 'The name foo returned is: {0}'.format(whatIsTheName)