如何检索 Python class 实例的 属性 的文档字符串?

How can I retrieve the docstring for a property of a Python class instance?

假设我有一个这样的class:

class TestCase(object):
    """Class docstring"""

    def meth(self):
        """Method docstring"""
        return 1

    @property
    def prop(self):
        """Property docstring"""
        return 2

我很容易获得 class 本身或常规方法的文档字符串:

tc = TestCase()

print(tc.__doc__)
# Class docstring

print(tc.meth.__doc__)
# Method docstring

但是,这种方法不适用于属性 - 相反,我得到 属性 getter 方法返回的任何对象的 __doc__ 属性(在这种情况下,int):

print(tc.prop.__doc__)
# int(x=0) -> int or long
# int(x, base=10) -> int or long
# ...

同样适用于 getattr(tc, "prop").__doc__getattr(tc.prop, "__doc__")

我知道 Python 的内省机制能够访问我正在寻找的文档字符串。例如,当我调用 help(tc) 时,我得到:

class TestCase(__builtin__.object)
 |  Class docstring
 |  
 |  Methods defined here:
 |  
 |  meth(self)
 |      Method docstring
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  prop
 |      Property docstring

help 如何访问 tc.prop 的文档字符串?

您正在尝试从实例访问 __doc__,该实例将首先尝试评估 属性,返回值可能没有属性 __doc__,或使用返回类型的__doc__

相反,您应该从 class 本身访问 property__doc__

TestCase.prop.__doc__

因此,要将其扩展到您的 class 实例,您将使用 __class__ 获取实例的 class,然后是 属性,最后是 __doc__:

tc.__class__.prop.__doc__

或使用type获取class:

type(tc).prop.__doc__