编程语言
首页 > 编程语言> > 如何在Python中记录类属性?

如何在Python中记录类属性?

作者:互联网

我正在编写一个轻量级类,其属性旨在可公开访问,并且有时仅在特定实例中被覆盖.在Python语言中没有为类属性或任何类型的属性创建文档字符串的规定.记录这些属性的可接受方式是什么?目前我正在做这样的事情:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
    """

    flight_speed = 691
    __doc__ += """
        flight_speed (691)
          The maximum speed that such a bird can attain.
    """

    nesting_grounds = "Raymond Luxury-Yacht"
    __doc__ += """
        nesting_grounds ("Raymond Luxury-Yacht")
          The locale where these birds congregate to reproduce.
    """

    def __init__(self, **keyargs):
        """Initialize the Albatross from the keyword arguments."""
        self.__dict__.update(keyargs)

这将导致类的docstring包含初始标准docstring部分,以及通过对__doc__进行扩充赋值为每个属性添加的行.

虽然在docstring style guidelines中似乎没有明确禁止这种风格,但它也没有作为选项提及.这里的优点是它提供了一种方法来记录属性及其定义,同时仍然创建一个可呈现的类docstring,并避免编写重复来自docstring的信息的注释.我仍然有点恼火,我必须实际写两次属性;我正在考虑使用docstring中值的字符串表示来至少避免重复默认值.

这是否是对特设社区公约的毁灭性违反?好吗?有没有更好的办法?例如,可以创建包含属性的值和文档字符串的字典,然后在类声明的末尾将内容添加到类__dict__和docstring;这样可以减少两次输入属性名称和值的需要.编辑:我认为,这最后一个想法实际上是不可能的,至少不是没有从数据动态构建整个类,这似乎是一个非常糟糕的想法,除非有其他理由这样做.

我对python很新,并且仍在研究编码风格的细节,所以也欢迎无关的批评.

解决方法:

为避免混淆:术语属性在python中有一个specific meaning.你所说的就是我们所说的class attributes.由于他们总是在他们的课堂上采取行动,我发现在课程的’doc字符串中记录它们是有意义的.像这样的东西:

class Albatross(object):
    """A bird with a flight speed exceeding that of an unladen swallow.

    Attributes:
        flight_speed     The maximum speed that such a bird can attain.
        nesting_grounds  The locale where these birds congregate to reproduce.
    """
    flight_speed = 691
    nesting_grounds = "Throatwarbler Man Grove"

我认为眼睛比你的例子中的方法容易得多.如果我真的想要在doc字符串中显示属性值的副本,我会将它们放在每个属性的描述旁边或下面.

请记住,在Python中,doc字符串是他们记录的对象的实际成员,而不仅仅是源代码注释.由于类属性变量本身不是对象,而是对对象的引用,因此它们无法保存自己的文档字符串.我想你可以为引用上的doc字符串做一个案例,或许可以描述“应该去哪里”而不是“实际上是什么”,但我发现在包含类doc字符串中这样做很容易.

标签:python,class,documentation,docstring,class-attributes
来源: https://codeday.me/bug/20190928/1826790.html