2013-12-20 141 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

相关问题