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

在python属性上放置文档字符串的正确方法是什么?,第1张

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

在getter上写文档字符串,因为1)就是

help(MyClass)
显示的内容,2)也是在Python文档中的完成方式-请参阅x.setter示例。

关于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”将被忽略。

因此,您应该在getter函数上为整个属性(getter和setter)编写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()


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5617341.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存