【问题标题】:How can I retrieve the docstring for a property of a Python class instance?如何检索 Python 类实例的属性的文档字符串?
【发布时间】:2016-11-02 06:19:14
【问题描述】:

假设我有这样的课程:

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

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

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

获取类本身或常规方法的文档字符串对我来说很容易:

tc = TestCase()

print(tc.__doc__)
# Class docstring

print(tc.meth.__doc__)
# Method docstring

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

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 的文档字符串?

【问题讨论】:

    标签: python properties docstring


    【解决方案1】:

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

    相反,您应该从类本身访问__doc__property

    TestCase.prop.__doc__
    

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

    tc.__class__.prop.__doc__
    

    或者使用type获取类:

    type(tc).prop.__doc__
    

    【讨论】:

    • 给定一个TestCase 的实例,我需要使用tc.__class__.prop.__doc__type(tc).prop.__doc__,但你是对的。
    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2019-09-04
    • 2014-04-16
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多