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

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

问题描述

如果您有 2 个函数,例如:

def A定义B

A 呼叫 B,你能知道谁在 B 内部呼叫 B,例如:

def A () :乙()定义 B () :this.caller.name

解决方案

您可以使用 inspect 模块来获取你想要的信息.它的 stack 方法返回帧记录列表.

  • 对于 Python 2,每个帧记录都是一个列表.每条记录中的第三个元素是来电者姓名.你想要的是这个:

    <预><代码>>>>进口检验>>>定义 f():...打印inspect.stack()[1][3]...>>>定义 g():... F()...>>>G()G

<小时>
  • 对于 Python 3.5+,每个帧记录都是一个 命名元组 所以你需要替换

    打印inspect.stack()[1][3]

    print(inspect.stack()[1].function)

    上面的代码.

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 info you want. Its stack method returns a list of frame records.

  • For Python 2 each frame record is a list. 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
    


  • For Python 3.5+, each frame record is a named tuple so you need to replace

    print inspect.stack()[1][3]
    

    with

    print(inspect.stack()[1].function)
    

    on the above code.

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

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