Python中注释代码的正确方法是什么?

6
我是一名有用的助手,可以为您翻译文本。
我正在阅读PEP8和Stack Overflow上的一些问题,但我想知道注释之间的空格:
假设我有这段代码:
class MyBrowser(QWebPage):
    ''' Settings for the browser.'''

    def __init__(self):
        QWebPage.__init__(self)
        # Specifies whether images are automatically loaded in web pages.
        self.settings().setAttribute(QWebSettings.AutoLoadImages, True)

    def userAgentForUrl(self, url):
        ''' Returns a User Agent that will be seen by the website. '''
        return "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15"

在注释和实际代码之间添加空行的最Pythonic方式是什么?我想向一些专家展示我的程序,并希望我的代码看起来更加专业。


我认为你当前的间距很好...还有什么构成专家? - Joran Beasley
专家指的是某公司的招聘经理。 - Vor
1
他们可能不是专家...但往往雇主愿意将你塑造成他们想要的人...他们想看到的是你对Python的概念和原则有一定的掌握,以及你知道编译与解释等方面的一些区别。 - Joran Beasley
4个回答

14

我不确定这是否代表了“社区标准”,但以下是 Google 的 Python 风格指南(涉及评论)。具体而言,是关于类的:

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

2

如果有疑问,可以查看标准库中的模块。

以下是来自timeit模块的摘录(由Guido van Rossum本人编写):

def print_exc(self, file=None):
    """Helper to print a traceback from the timed code.

    Typical use:

        t = Timer(...)       # outside the try/except
        try:
            t.timeit(...)    # or t.repeat(...)
        except:
            t.print_exc()

    The advantage over the standard traceback is that source lines
    in the compiled template will be displayed.

    The optional file argument directs where the traceback is
    sent; it defaults to sys.stderr.
    """
    import linecache, traceback
    if self.src is not None:
        linecache.cache[dummy_src_name] = (len(self.src),
                                           None,
                                           self.src.split("\n"),
                                           dummy_src_name)
    # else the source is already stored somewhere else

    traceback.print_exc(file=file)

1
从Python之禅中可以得出:“可读性很重要。” 无论您的团队认为什么最易读,我都会这样做。

1
通常情况下,但有时候更可读的是Python社区(而不是你个人)发现的(我给你+1,因为总体上来说这是正确的)。 - Joran Beasley
我经常发现如果没有注释,我的代码就不太易读,因为我已经知道它的功能,但我觉得这并不意味着我不应该加上注释。 - djechlin
我不认为你偏爱的就是最好的。我曾经和一些人一起工作,他们遵循奇怪的标准(例如三个空格缩进)。他们喜欢自己的代码,但是团队中其他人都无法忍受看它。 - aaaa bbbb
说实话,我很少在我的Python代码中包含注释...我使用自我记录的变量/函数名称,这通常已经足够了...尽管如此,我可能不会展示我的没有注释的代码.. - Joran Beasley
可能吧……但是我们中有多少人实际上编写的代码是整个Python社区看过或者将会看到的呢?如果我能读懂它,而且我的同事们没有对我抱怨,我认为这就足够了。是的,我从来没有见过一个程序员不敢在同事面前表达自己的想法 :D - brian buck
如果你把答案改成“无论你的团队认为最易读的”,我会给你返还一个分数。 - aaaa bbbb

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接