在python属性上放置文档字符串的正确方法是什么? [英] What is the right way to put a docstring on Python property?
问题描述
我应该制作几个文档字符串,还是只写一个(我应该放在哪里)?
Should I make several docstrings, or just one (and where should I put it)?
@property
def x(self):
return 0
@x.setter
def x(self, values):
pass
我看到 property()
接受doc参数。
I see that property()
accepts a doc argument.
推荐答案
在吸气剂上写文档字符串,因为1)这就是 help(MyClass)
显示的内容,以及2)这也是在 Python文档中进行的操作-请参阅x.setter示例。
Write the docstring on the getter, because 1) that's what help(MyClass)
shows, and 2) it's also how it's done in the Python docs -- see the x.setter example.
关于1):
class C(object):
@property
def x(self):
"""Get x"""
return getattr(self, '_x', 42)
@x.setter
def x(self, value):
"""Set x"""
self._x = value
然后:
>>> c = C()
>>> help(c)
Help on C in module __main__ object:
class C(__builtin__.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| x
| Get x
>>>
请注意,设置器的文档字符串 Set x将被忽略。
Note that the setter's docstring "Set x" is ignored.
因此,应在getter函数上为整个属性(getter和setter)编写docstring,以使其可见。好的属性文档字符串的示例可能是:
So you should write the docstring for the entire property (getter and setter) on the getter function for it to be visible. An example of a good property docstring might be:
class Serial(object):
@property
def baudrate(self):
"""Get or set the current baudrate. Setting the baudrate to a new value
will reconfigure the serial port automatically.
"""
return self._baudrate
@baudrate.setter
def baudrate(self, value):
if self._baudrate != value:
self._baudrate = value
self._reconfigure_port()
这篇关于在python属性上放置文档字符串的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!