如何在被调用方法中获取调用者的方法名称? [英] How to get the caller's method name in the called method?

查看:79
本文介绍了如何在被调用方法中获取调用者的方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python:如何在被调用方法中获取调用者的方法名称?

Python: How to get the caller's method name in the called method?

假设我有2种方法:

def method1(self):
    ...
    a = A.method2()

def method2(self):
    ...

如果我不想对method1进行任何更改,如何在method2中获取调用方的名称(在本示例中,名称为method1)?

If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?

推荐答案

inspect.getframeinfo and other related functions in inspect can help:

>>> 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

此自省旨在帮助调试和开发;建议不要出于生产功能目的而依赖它.

this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.

这篇关于如何在被调用方法中获取调用者的方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆