Python - 我可以访问给我打电话的对象吗?

时间:2010-03-05 15:19:27

标签: python oop function-calls

如果我有这个:

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 个答案:

答案 0 :(得分: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>}

答案 1 :(得分:3)

这是一个快速入侵,获取堆栈并从最后一帧获得本地人访问自己

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 :)

答案 2 :(得分:1)

使用inspect.stack()f_locals['self']检查堆栈。然后,您可以使用{{1}}

从列表中的每个元素获取实例