Python - 无法在运行时获取 class 方法的对象以提取文档字符串

Python - Can not get object of class method at runtime to extract doc-string

我试图在运行时获取 class 方法的文档字符串。我面临的问题是该方法在运行时未记录在 globals() 中。

下面的代码说明了普通函数被记录在全局变量中,但 class 方法没有。

import datetime, inspect

class Age:
    """
    test Ager DOCstring
    """

    def __init__(self):
        pass

    def get_age(self, yob):
        """
        Calculate age using date of birth.
        """
        outerframe = inspect.currentframe()
        functionname = outerframe.f_code.co_name
        func_details = globals()[ functionname ]
        print('class_method:', func_details)

        year_today = datetime.datetime.today().year
        age = year_today-yob
        return age


def calc_age(yob):
    outerframe = inspect.currentframe()
    functionname = outerframe.f_code.co_name
    func_details = globals()[ functionname ]
    print('normal_function:', func_details)

    year_today = datetime.datetime.today().year
    age = year_today-yob
    return age


if __name__ == "__main__":
    calc_age(1998)
    ager = Age()
    ager.get_age(1990) # will raise KeyError

此行为的原因是什么,我该如何解决?

您的方法不是全局值,它作为属性存在于您的 class 中。您可以在 classes __dict__ 属性中找到它,但是:

Age.__dict__['get_age']