Skip to content Skip to sidebar Skip to footer

Python - Can I Access The Object Who Call Me?

If I have this: class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def other

Solution 1:

If this is for debugging purposes you can use inspect.currentframe():

import inspect

classC:
    defotherFunction(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>}

Solution 2:

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__.Ainstanceat0x00C1CAA8> called me :)
<__main__.Binstanceat0x00C1CAA8> called me :)

Solution 3:

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']

Post a Comment for "Python - Can I Access The Object Who Call Me?"