python - 将文档字符串放在 Python 属性上的正确方法是什么?

标签 python properties decorator

我应该制作几个文档字符串,还是只制作一个(我应该把它放在哪里)?

@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/

相关文章:

python - 如何计算时针和分针之间的角度?

javascript - knockout 在 Pyramid 中表现不正确

python - 指向另一个对象的属性并添加你自己的

c# - DropDownList 多了一个值

用户控件的 ASP.NET 验证消息 "Attribute ... is not a valid attribute of element ..."

java - Spring - 用新的属性文件值替换 bean 属性值

python - 为每个索引制作一个具有不同颜色的颜色网格

python - 如何捕获装饰器中引发的错误?

python - 为什么装饰器模块强制我将内部函数提升到外部水平?

python - 为多个属性定义@property 的函数