3

私がこれを持っている場合:

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

4

3 に答える 3

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>}
于 2010-03-05T15:32:48.160 に答える
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 :)
于 2010-03-05T15:32:19.393 に答える
1

の検査モジュールでスタックを調べますinspect.stack()。次に、リスト内の各要素からインスタンスを取得できますf_locals['self']

于 2010-03-05T15:25:06.647 に答える