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

用Python注释代码的正确方法是什么?,python,comments,Python,Comments,我正在阅读PEP8和一些关于堆栈溢出的问题,但我想知道注释之间的空格: 假设我有以下代码: class MyBrowser(QWebPage): ''' Settings for the browser.''' def __init__(self): QWebPage.__init__(self) # Specifies whether images are automatically loaded in web pages. s

我正在阅读PEP8和一些关于堆栈溢出的问题,但我想知道注释之间的空格:

假设我有以下代码:

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"

在注释和实际代码之间放置空行的最有技巧的方法是什么?我想向一些专家展示我的程序。希望我的代码看起来更专业。

来自Python的禅宗:“可读性很重要。您的团队发现可读性最好的就是我所做的。

如果有疑问,请查看标准库中的模型

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


我不知道这是否代表了“社区标准”,但这里是(因为它们与评论相关)。具体类别:

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."""

与其给出代码片段,不如使用sphinx查看最常用的代码片段,并将文档与代码进行比较


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

我认为您当前的间距很好。。。什么是专家?所谓专家,我指的是一些公司的招聘经理,他们可能不是专家。。。。很多时候,雇主都愿意把你塑造成他们想要的样子。。。他们想看到的是,您掌握了python的概念和原理。。。您知道编译与解释之间的一些差异。一般来说,python大众(与您个人相反)有时会觉得可读性更高(我给了您+1,但一般来说这是正确的),我经常发现我的代码在没有注释的情况下可读性较差,因为我已经知道它的功能,但我觉得这并不意味着我不应该包括评论。我不同意你喜欢的是最好的。我曾与遵循奇怪标准(例如三个空格缩进)的人共事过。他们喜欢他们的代码。小组中没有其他人可以看它。TBH我很少在python中添加注释。。。我使用自文档化变量/函数名,这通常就足够了。。。也就是说,我可能不会展示我的无注释代码……可能……但我们中有多少人实际拥有python社区已经看到/将要看到的代码?如果我能读懂它,而我的同事们没有对我发牢骚,我觉得这就足够了。是的,我从未见过一个程序员不向同事倾诉心声:D
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."""