Python - Can I access the object who call me?

别说谁变了你拦得住时间么 提交于 2019-12-18 13:36:59

问题


If I have this:

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.

Note: This has to be done without changing otherFunction signature


回答1:


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>}



回答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__.A instance at 0x00C1CAA8> called me :)
<__main__.B instance at 0x00C1CAA8> called me :)



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



来源:https://stackoverflow.com/questions/2387756/python-can-i-access-the-object-who-call-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!