2013-03-11 61 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