gpt4 book ai didi

Python - 我可以访问给我打电话的对象吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:50 25 4
gpt4 key购买 nike

如果我有这个:

class A:
def callFunction(self, obj):
obj.otherFunction()

class B:
def callFunction(self, obj):
obj.otherFunction()

class C:
def otherFunction(self):
# here I wan't to have acces to the instance of A or B who call me.

...

# in main or other object (not matter where)
a = A()
b = B()
c = C()
a.callFunction(c) # How 'c' know that is called by an instance of A...
b.callFunction(c) # ... or B

不管是设计还是其他问题,这只是一个求知欲的问题。

注意:这必须在不改变的情况下完成 otherFunction signature

最佳答案

如果这是为了调试目的,您可以使用 inspect.currentframe():

import inspect

class C:
def otherFunction(self):
print inspect.currentframe().f_back.f_locals

这是输出:

>>> A().callFunction(C())
{'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951ef2c>}

关于Python - 我可以访问给我打电话的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2387756/

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