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
尽管有设计或其他方面的问题,这只是一个好奇心的问题。
注意:这必须在不改变 otherFunction
的函数签名 的情况下完成。
3 个回答
1
使用inspect模块来查看堆栈,方法是调用inspect.stack()
。然后,你可以通过f_locals['self']
从列表中的每个元素获取实例。
3
这里有个简单的小技巧,获取当前的调用栈,然后从最后一帧中获取局部变量,这样就可以访问到self了。
class A:
def callFunction(self, obj):
obj.otherFunction()
class B:
def callFunction(self, obj):
obj.otherFunction()
import inspect
class C:
def otherFunction(self):
lastFrame = inspect.stack()[1][0]
print lastFrame.f_locals['self'], "called me :)"
c = C()
A().callFunction(c)
B().callFunction(c)
输出结果:
<__main__.A instance at 0x00C1CAA8> called me :)
<__main__.B instance at 0x00C1CAA8> called me :)
11
如果你是为了调试程序,可以使用 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>}