Tom
2010-03-05 15:24:20
+1 for the most simple solution :-)
Aaron Digulla
2010-03-05 15:25:31
Is really simple.. but.. What if I can't do this? What if A and B are objects from a library or something like that? It still possible even without doing this?
unkiwii
2010-03-05 15:30:32
A:
Examine the stack with the inspect module with inspect.stack()
. You can then get the instance from each element in the list with f_locals['self']
Aaron Digulla
2010-03-05 15:25:06
But i want to acces the OBJECT who is calling me.. not just the name of the class.. I wan't to acces the instance
unkiwii
2010-03-05 15:28:58
Use the inspect module to access `tb_frame` in the each item of the stacktrace and then you can find the instance in `f_locals['self']`
Aaron Digulla
2010-03-05 15:30:54
+2
A:
Here is a quick hack, get the stack and from last frame get locals to access 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)
output:
<__main__.A instance at 0x00C1CAA8> called me :)
<__main__.B instance at 0x00C1CAA8> called me :)
Anurag Uniyal
2010-03-05 15:32:19
+2
A:
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
Here is the output:
>>> A().callFunction(C())
{'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951ef2c>}
Nadia Alramli
2010-03-05 15:32:48