我使用下面的代码来get the caller's method name in the called method :
import inspect
def B():
outerframe = inspect.currentframe().f_back
functionname = outerframe.f_code.co_name
docstring = ??
return "caller's name: {0}, docsting: {1}".format(functionname, docstring)
def A():
"""docstring for A"""
return B()
print A()
但我也想在被调用方法中从调用者的方法中获取文档字符串。我该怎么做?
请您参考如下方法:
你不能,因为你没有对函数对象的引用。它是具有 __doc__ 属性的函数对象,而不是关联的代码对象。
您必须使用文件名和行号信息来尝试对文档字符串可能是什么做出有根据的猜测,但由于 Python 的动态特性,不能保证它是正确的和最新的。
