【问题标题】:How to get who invoked a function or method?如何获取谁调用了函数或方法?
【发布时间】:2014-01-09 10:27:03
【问题描述】:

这是我需要的:

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 拥有所有这些魔力,但我一直没能找到它。

编辑

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

【问题讨论】:

  • 在最后一个例子中,输出不应该是invoke_f?
  • 是的!谢谢@xndrme。

标签: python reflection introspection


【解决方案1】:

像这样:

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

【讨论】:

  • 你从这里得到一个字符串。如何获取函数对象?
猜你喜欢
  • 2010-11-25
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
相关资源
最近更新 更多