2013-03-11 60 views
2

我用下面的代码的文档字符串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() 

,但我也想从来电者的方法的文档字符串中调用的方法。我怎么做?

回答

1

你不能,因为你没有给功能对象的引用。它是具有__doc__属性的函数对象,而不是关联的代码对象。

您必须使用文件名和linenumber信息来尝试对文档字符串的内容进行有根据的猜测,但是由于Python的动态特性并不能保证是正确的和当前的。

0

我不一定会提示,但您可以随时使用globals()来按名称查找函数。它会去是这样的:

import inspect 

def B(): 
    """test""" 
    outerframe = inspect.currentframe().f_back 
    functionname = outerframe.f_code.co_name 
    docstring = globals()[ functionname ].__doc__ 
    return "caller's name: {0}, docsting: {1}".format(functionname, docstring) 

def A(): 
    """docstring for A""" 
    return B() 

print A() 
+0

函数名称不一定是它的存储名称;您可以像任何其他对象一样重新分配函数。它们也不总是全局的,类的方法当然不是全局的。 – 2013-03-11 17:02:39

+0

是的,就像我说的,当然不会推荐它,但如果你绝对需要在小程序中快速修复,那么这是一种可能性 – 2013-03-11 22:05:37