Python-我可以访问调用我的对象吗? [英] Python - Can I access the object who call me?
本文介绍了Python-我可以访问调用我的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这个:
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
尽管有设计或其他问题,但这只是一个有疑问的问题.
Despite the design or other issues, this is only a question of an inquiring mind.
注意:必须在不更改的情况下完成 otherFunction
签名
Note: This has to be done without changing otherFunction
signature
推荐答案
如果这是出于调试目的,则可以使用inspect.currentframe():
If this is for debugging purposes you can use 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-我可以访问调用我的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文