5

我正在阅读 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 方式是什么?我想向一些专家展示我的程序。并希望我的代码看起来更专业。

4

4 回答 4

12

我不知道这是否代表“社区标准”,但这里是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."""
于 2012-12-12T22:58:49.300 回答
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)
于 2012-12-12T22:57:48.427 回答
1

来自 Python 之禅:“可读性很重要。” 无论您的团队发现什么最易读,我都会这样做。

于 2012-12-12T22:54:35.863 回答
0

不要给出片段,而是查看使用 sphinx 的最常用的CPython,并将文档与代码进行比较。

文档永远不会不同步,因为注释就在代码中。

于 2018-10-25T10:55:54.560 回答