在Python属性上放置docstring的正确方法是什么?

2024-05-14 23:34:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该做几个docstring,还是只做一个(我应该把它放在哪里)?

@property
def x(self):
     return 0
@x.setter
def x(self, values):
     pass

我看到property()接受doc参数。


Tags: self参数docreturndefpropertypasssetter
1条回答
网友
1楼 · 发布于 2024-05-14 23:34:06

在getter上编写docstring,因为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的docstring“Set x”被忽略。

因此,应该为getter函数的整个属性(getter和setter)编写docstring,使其可见。一个好的docstring属性示例可能是:

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()

相关问题 更多 >

    热门问题