Python我可以访问调用我的对象吗?

2024-09-25 08:38:34 发布

您现在位置: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签名的情况下完成


Tags: orofthetoinstanceselfobjhere
3条回答

如果这是为了调试目的,您可以使用检查电流帧():

import inspect

class C:
    def otherFunction(self):
        print inspect.currentframe().f_back.f_locals

输出如下:

^{pr2}$

使用inspect module和{}检查堆栈。然后可以使用f_locals['self']从列表中的每个元素获取实例

这里是一个快速的黑客,得到堆栈和从最后一帧获得本地访问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)

输出:

^{pr2}$

相关问题 更多 >