在Python中的另一个函数中调用函数名称? [英] Getting the caller function name inside another function in Python?

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

问题描述

如果您有两个功能,如:

  def A 
def B

A呼叫B,您可以得到谁在B内呼叫B,如:



def $($)
B()

def B():
this.caller.name


解决方案

您可以使用检查模块以获取调用堆栈。它返回帧记录的列表。每个记录中的第三个元素是调用者名称。你想要的是:

 >>>进口检查
>>> def f():
... print inspect.stack()[1] [3]
...
>>> def g():
... f()
...
>>> g()
g

当然,最好检查足够的帧记录在尝试访问特定索引之前存在。


If you have 2 functions like:

def A
def B

and A calls B, can you get who is calling B inside B, like:

def A () :
    B ()

def B () :
    this.caller.name

解决方案

You can use the inspect module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this:

>>> import inspect
>>> def f():
...     print inspect.stack()[1][3]
...
>>> def g():
...     f()
...
>>> g()
g

Of course, it is a good idea to check that enough frame records exist before trying to access a particular index.

这篇关于在Python中的另一个函数中调用函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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