我应该制作几个文档字符串,还是只制作一个(我应该把它放在哪里)?
@property
def x(self):
return 0
@x.setter
def x(self, values):
pass
我看到 property()
接受一个 doc 参数。
最佳答案
在 getter 上写入文档字符串,因为 1) 这就是 help(MyClass)
显示的内容,以及 2) 它也是在 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
>>>
请注意,setter 的文档字符串“Set x”会被忽略。
因此,您应该在 getter 函数上编写整个属性(getter 和 setter)的文档字符串,以使其可见。一个好的属性文档字符串的例子可能是:
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 - 将文档字符串放在 Python 属性上的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16025462/