Python:如何在被调用方法中获取调用者的方法名?
假设我有两种方法:
def method1(self):
...
a = A.method2()
def method2(self):
...
如果我不想对method1做任何更改,如何在method2中获取调用者的名字(本例中为method1)?
最佳答案
inspect.getframeinfo和 inspect
中的其他相关功能可以提供帮助:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
这种自省(introspection)旨在帮助调试和开发;不建议将其用于生产功能目的。
https://stackoverflow.com/questions/2654113/