def applejuice(q):
print THE FUNCTION NAME!
Dovrebbe risultare in "applejuice" come stringa.Come stampare il nome della funzione come una stringa in Python dall'interno di quella funzione
def applejuice(q):
print THE FUNCTION NAME!
Dovrebbe risultare in "applejuice" come stringa.Come stampare il nome della funzione come una stringa in Python dall'interno di quella funzione
Questo funziona anche:
import sys
def applejuice(q):
func_name = sys._getframe().f_code.co_name
print func_name
È necessario spiegare qual è il problema. Perché la risposta alla tua domanda è:
print "applejuice"
forse intende: def func (anothah_func): print anothah_func's name – wilhelmtell
Beh, questo è sicuramente possibile. Vedremo se dice qual è il problema. –
def applejuice(**args):
print "Running the function 'applejuice'"
pass
o l'uso:
myfunc.__name__
>>> print applejuice.__name__
'applejuice'
Inoltre, vedere how-to-get-the-function-name-as-string-in-python
upvote per 'myfunc .__ name__' – philshem
import traceback
def applejuice(q):
stack = traceback.extract_stack()
(filename, line, procname, text) = stack[-1]
print procname
Presumo che ciò viene utilizzato per il debugging, per cui si potrebbe desidera esaminare le altre procedure offerte dallo traceback
module. Ti permettono di stampare l'intero stack di chiamate, tracce di eccezione, ecc
Un altro modo
import inspect
def applejuice(q):
print inspect.getframeinfo(inspect.currentframe())[2]
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)
Questo sito mi ha dato una spiegazione decente di come funziona sys._getframe.f_code.co_name che restituisce il nome della funzione.
http://code.activestate.com/recipes/66062-determining-current-function-name/
Wlecome to SO! per favore, pensa a fornire spiegazioni e non solo a link esterni. –
Vedi http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question-on-so/25128#25128 –
Dalla risposta che ha scelto il possibile concludere che questo era davvero un duplicato. In effetti, esisteva già una domanda quasi identica: http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python –
Non sono d'accordo che si tratti di un duplicato di # 251464 - sembra che questa domanda sia l'inversa. –