【问题标题】:Get reference to instance of class that calls a function获取对调用函数的类实例的引用
【发布时间】:2019-08-22 20:13:44
【问题描述】:

我正在尝试跟踪给定函数的函数调用层次结构(回溯),但以一种允许我获取对包含函数作为属性的类的引用的方式。获取类实例的引用也很好。

如果我有一个 A 类的对象,它具有函数 do_work 并且函数 do_work 调用函数 f,我想知道在 f 内部是哪个 A 实例调用了它。

目前,使用inspect 模块,我得到了正确的函数调用顺序,但这不包括对将函数作为属性保存的类或对象实例的任何引用:

import inspect


class A:
    def __init__(self, name):
        self.name = name

    def do_work(self):
        return f()


def f():
    return inspect.stack()


a = A("test")
print(a.do_work())
[
FrameInfo(frame=<... line 13, code f>, code_context=['return inspect.stack()'])
FrameInfo(frame=<..., line 9, code do_work>, code_context=['return f()']),
FrameInfo(frame=<..., line 17, code <module>>, code_context=['print(a.do_work())'])
]

我想从f 获得对a 对象实例或至少对A 类的引用。

【问题讨论】:

    标签: python inspect


    【解决方案1】:

    给定您感兴趣的框架的 FrameInfo:

    frame_info = inspect.stack()[1]
    # FrameInfo(frame=<frame at 0x107b959d8, file ..., line 8, code do_work>, filename='...', lineno=8, function='do_work', code_context=['        return f()\\n'], index=0)
    

    您可以通过以下方式访问a 对象(在该框架中称为self):

    frame_info.frame.f_locals['self']
    # <__main__.A object at 0x107b86a20>
    

    还有它的类名using:

    frame_info.frame.f_locals['self'].__class__.__name__
    # A
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2021-10-08
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      相关资源
      最近更新 更多