gpt4 book ai didi

python - 内省(introspection)调用对象

转载 作者:太空狗 更新时间:2023-10-29 17:24:01 28 4
gpt4 key购买 nike

我如何从 b.func() 内省(introspection) A 的实例(即 A 的实例的 self ):

class A():
def go(self):
b=B()
b.func()

class B():
def func(self):
# Introspect to find the calling A instance here

最佳答案

通常我们不希望 func 能够访问 A 的调用实例,因为这会破坏 encapsulation .在 b.func 中,您应该可以访问传递的任何 args 和 kwargs,实例 b 的状态/属性(通过 self 此处) ,以及周围的任何全局变量。

如果你想知道一个调用对象,有效的方法是:

  1. 将调用对象作为参数传递给函数
  2. 在使用func 之前的某个时候,在b 实例上显式添加调用者的句柄,然后通过self 访问该句柄。

但是,在排除免责声明的情况下,仍然值得知道 python 的内省(introspection)功能强大到足以在某些情况下访问调用方模块。在 CPython 实现中,下面是如何在不更改接口(interface)的情况下访问调用 A 实例的方法:

class A():
def go(self):
b=B()
b.func()

class B():
def func(self):
import inspect
print inspect.currentframe().f_back.f_locals['self']

if __name__ == '__main__':
a = A()
a.go()

输出:

<__main__.A instance at 0x15bd9e0>

有时了解这可能是调试代码的有用技巧。但是,在 B.func 出于任何原因实际需要使用 A 的情况下,像这样访问堆栈帧并不是一个明智的设计决定。

关于python - 内省(introspection)调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272326/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com