2010-03-05 67 views
3

如果我有這樣的: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簽名

回答

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

檢查與inspect moduleinspect.stack()堆棧來完成。然後,您可以從列表中的每個元素與f_locals['self']

+0

但我想存取權限是誰喊我對象..不只是類的名稱。我wan't進入電影實例 – 2010-03-05 15:28:58

+0

使用檢查模塊訪問' tb_frame'在stacktrace的每一項中,然後你可以在'f_locals ['self']'中找到實例' – 2010-03-05 15:30:54

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 :) 
相關問題