2013-12-20 506 views
2

這就是我需要:如何獲取誰調用了一個函數或方法?

def get_invoker(): 
    # your magic here 

# invoker.py  

def f(): 
    invoker = get_invoker() 
    print(invoker) 


# module1.py 
class C(object): 
    def invoke_f(self): 
     f() 


f() 
# print <module1> 

c = C() 
c.invoke_f() 
# print C.invoke_f 

這可能嗎?我知道模特inspect擁有所有這些魔力,但我一直無法找到它。

編輯

我想獲得的函數對象(或模塊)。不只是名字。

+0

在最後一個例子,輸出不應該是'invoke_f'? –

+0

是的!謝謝@xndrme。 – santiagobasulto

回答

1

這樣的:

>>> import inspect 
>>> def called_function(): 
...  print inspect.stack()[1][3] 
... 
>>> def caller(): 
...  called_function() 
... 
>>> caller() 
caller 
+0

你從這裏得到一個字符串。你如何獲得函數對象? – santiagobasulto

相關問題