【问题标题】:Python property docstring only prints for help on the whole classPython 属性文档字符串仅打印整个类的帮助
【发布时间】:2019-03-06 17:58:40
【问题描述】:

我正在尝试在 python 模块中记录 @property,但无法让文档字符串显示在属性的帮助中。我想致电 help(class.property) 以仅打印该属性的帮助。

这是一个例子:

class ClassWithStringProperty(object):
    def __init__(self):
        self._str_obj = "'{0:02d}, {1}'.format(thingy['number'], thingy['description']"

    @property
    def str_obj(self):
        """
        A configurable formatting string that is eval()'ed for data export
        """
        return self._str_obj

    @str_obj.setter
    def str_obj(self, str_obj):
        self._str_obj = str_obj

当我导入并尝试获取帮助时,它适用于整个班级,但不适用于单个属性:

In [1]: from property_docstring import ClassWithStringProperty
In [2]: cwp = ClassWithStringProperty()
In [4]: help(cwp)
Help on ClassWithStringProperty in module property_docstring object:

class ClassWithStringProperty(__builtin__.object)  
 |  Methods defined here:
 |
 |  __init__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  str_obj
 |      A configurable formatting string that is eval()'ed for data export

In [5]: help(cwp.str_obj)
no Python documentation found for "'{0:02d}, {1}'.format(thingy['number'], thingy['description']"

正如您在In [4] 的输出中看到的那样,文档字符串在str_obj 下打印,但在In [5] 中却显示没有Python 文档。

我怎样才能允许自己访问@property 的文档而不必列出整个班级的文档?

【问题讨论】:

  • cwp.str_obj 是调用 getter 的结果,_str_obj,而不是 getter 方法本身。这就是使用属性的要点

标签: python python-2.7 properties docstring


【解决方案1】:

您正在访问实例上的属性,导致 getter 被调用 并将结果传递给 help() 函数。 getter 返回的值没有文档字符串。

请注意,这里实际上并没有使用help(class.property),而是使用help(<em><strong>instance</strong></em>.property)

您需要在课堂上寻求帮助;如果您只有实例,请使用type() 为您提供课程:

help(type(cwr).str_obj)

或者,如果您已经上过该课程,请在该课程上寻求帮助:

help(ClassWithStringProperty.str_obj)

help(instance) 自动检测到你有一个实例并在类上为你提供帮助,但是对于属性的结果不能这样做,当@987654328 时,与实例(以及与类)的关系消失了@ 被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多