获取调用函数的 class 实例的引用
Get reference to instance of class that calls a function
我正在尝试跟踪给定函数的函数调用层次结构(回溯),但以一种允许我获得对 class 的引用的方式,该引用将函数作为属性保存。获取 class 实例 的引用也很好。
如果我有一个 class A
的对象,它有函数 do_work
并且函数 do_work
调用函数 f
,我想知道里面f
A
的哪个实例调用了它。
目前,使用 inspect
模块我得到了正确的函数调用顺序,但这不包括对 class 的任何引用或将函数作为属性保存的对象实例:
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
class 的引用。
鉴于您感兴趣的框架的 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>
以及它的 class 名称 using:
frame_info.frame.f_locals['self'].__class__.__name__
# A
我正在尝试跟踪给定函数的函数调用层次结构(回溯),但以一种允许我获得对 class 的引用的方式,该引用将函数作为属性保存。获取 class 实例 的引用也很好。
如果我有一个 class A
的对象,它有函数 do_work
并且函数 do_work
调用函数 f
,我想知道里面f
A
的哪个实例调用了它。
目前,使用 inspect
模块我得到了正确的函数调用顺序,但这不包括对 class 的任何引用或将函数作为属性保存的对象实例:
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
class 的引用。
鉴于您感兴趣的框架的 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>
以及它的 class 名称 using:
frame_info.frame.f_locals['self'].__class__.__name__
# A