我如何得到一个函数的名字作为字符串?

def foo():
    pass

>>> name_of(foo)
"foo"

当前回答

import inspect

def foo():
   print(inspect.stack()[0][3])

在哪里

Stack()[0]是调用者 [3]是方法的字符串名称

其他回答

Try

import sys
fn_name = sys._getframe().f_code.co_name

进一步的参考 https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html

如果你对类方法也感兴趣,Python 3.3+除了__name__还有__qualname__。

def my_function():
    pass

class MyClass(object):
    def method(self):
        pass

print(my_function.__name__)         # gives "my_function"
print(MyClass.method.__name__)      # gives "method"

print(my_function.__qualname__)     # gives "my_function"
print(MyClass.method.__qualname__)  # gives "MyClass.method"

你可以通过使用特殊的__name__变量来获取一个字符串形式的函数名。

def my_function():
    pass

print(my_function.__name__) # prints "my_function"

sys._getframe()并不保证在Python的所有实现中都可用(参见ref),你可以使用traceback模块来做同样的事情,例如。

import traceback
def who_am_i():
   stack = traceback.extract_stack()
   filename, codeline, funcName, text = stack[-2]

   return funcName

调用stack[-1]将返回当前进程的详细信息。

my_function.__name__

使用__name__是首选方法,因为它是统一应用的。与func_name不同,它也适用于内置函数:

>>> import time
>>> time.time.func_name
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__ 
'time'

此外,双下划线向读者表明这是一个特殊属性。作为奖励,类和模块也有__name__属性,所以你只需要记住一个特殊的名称。