1

现在,我有两种方法可以在 python 中获取当前函数/方法的名称

基于函数

>>> import inspect
>>> import sys
>>> def hello():
...     print(inspect.stack()[0][3])
...     print(sys._getframe(  ).f_code.co_name)
...
>>> hello()
hello
hello

基于类

>>> class Hello(object):
...     def hello(self):
...         print(inspect.stack()[0][3])
...         print(sys._getframe(  ).f_code.co_name)
...
>>> obj = Hello()
>>> obj.hello()
hello
hello

还有其他比这更简单有效的方法吗?

4

1 回答 1

2

我相信这篇文章回答了你的问题: Determine function name from within that function (without using traceback)

没有内置的方法来获取函数的名称。浏览一下您的代码,我相信这些是您最容易遇到的。

虽然我可能错了,请随时纠正我。

于 2019-09-10T07:54:52.383 回答