【发布时间】: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