什么是 PEP8 / Python 多行注释的最佳实践?



我使用了很多代码模式:

1    class myTest():
2        counter = 0      # use this as general counter
3        name_code = ''   # this is the name encoded using the
4                         # standard as defined in ...
5        category = ''    # category of test

4号线不是PEP8标准。#应该在位置5,这看起来IMHO只是丑陋:

3        name_code = ''   # this is the name encoded using the
4        #                  standard as defined in ...

你如何评价这种模式?什么是最佳实践?

我会在类docstring中记录变量,因为它们是类的静态成员。这样,您的实际代码就变得更加紧凑,更容易阅读和消化:

class myTest():
"""Test class which does something.
Attributes:
counter (int): Use this as general counter.
name_code (str): This is the name encoded using the
standard as defined in this long piece of text.
Just continue the lines with one level of indentation
for as long as you want.
category (str): Category of the test.
"""
counter = 0
name_code = ''
category = ''

我在这里使用了谷歌风格的Python文档字符串,因为这只是我喜欢的风格。

我会将它们作为docstring进行处理,因此它们实际上可用于Sphinx等其他工具,并可用于例如生成文档:

class myTest():
counter = 0
"""use this as general counter"""
name_code = ''
"""this is the name encoded using the standard as defined in ..."""
category = ''
"""category of test"""

文档字符串通常是多行字符串,因此可以根据需要扩展到多行。

例如,这里有一个类,我用docstring记录了它的属性,允许从中自动生成文档

最新更新