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

时间:2019-11-05 09:59:34

标签: python pep8

我使用很多代码模式:

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上看起来很丑陋的恕我直言:

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

您如何评论这种模式? 什么是最佳做法?

2 个答案:

答案 0 :(得分:2)

我将在类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 = ''

我在这里使用了Google style Python docstring,因为这只是我偏爱的样式。

答案 1 :(得分:-1)

我会将它们设为docstrings,因此实际上它们可用于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"""

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

例如,here's是一个类,该类的属性我已经使用文档字符串进行了文档记录,从而可以自动从中生成this文档。

相关问题