Skip to main content
 首页 » 编程设计

python之如何获得谁调用了函数或方法

2025年05月04日10daizhj

这是我需要的:

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 

这可能吗?我知道 modlue inspect 具有所有这些魔力,但我一直无法找到它。

编辑:

我想获取函数对象(或模块)。不仅仅是名字。

请您参考如下方法:

像这样:

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