Python属性docstring仅打印以获取整个类的帮助

问题描述 投票:0回答:1

我正在尝试在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]的输出中所看到的,docstring在str_obj下打印,但在In [5]中它表示没有Python文档。

如何在不必列出整个班级文档的情况下允许自己访问@ property的文档?

python python-2.7 properties docstring
1个回答
0
投票

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

请注意,您实际上并未使用help(class.property),而是使用help(instance.property)

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

help(type(cwr).str_obj)

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

help(ClassWithStringProperty.str_obj)

help(instance)会自动检测到你有一个实例,并为你提供类的帮助,但是对于属性的结果无法做到,当调用help()时,与实例的关系(以及对类的关系)就消失了。

© www.soinside.com 2019 - 2024. All rights reserved.