【问题标题】:Is there a way to put comments in multiline code?有没有办法在多行代码中添加注释?
【发布时间】:2013-07-11 22:27:46
【问题描述】:

这不起作用:

something = \
    line_of_code * \    #  Comment
    another_line_of_code * \    #  Comment
    and_another_one * \         #  Comment
    etc

这也不行:

something = \
    #  Comment \
    line_of_code * \
    #  Comment \
    another_line_of_code * ...

这也不行:

something = \
    ''' Comment ''' \
    line_of_code * \
    ''' Comment ''' \
    another_line_of_code * ...

有没有办法让代码中的cmets分成多行?

【问题讨论】:

    标签: python comments format multiline backslash


    【解决方案1】:

    这样做:

    a, b, c, d = range(1, 5)
    
    result = (
        # First is 1
        a *
        # Then goes 2, result is 2 now
        b *
        # And then 3, result is 6
        c *
        # And 4, result should be 24
        d
    )
    

    实际上,according to PEP8 括号比斜杠更受欢迎,当将某些内容分成多行时:

    包装长行的首选方法是在圆括号、方括号和大括号内使用 Python 隐含的续行。通过将表达式括在括号中,可以将长行分成多行。应该优先使用这些,而不是使用反斜杠来续行。

    在您的情况下,它还允许放置 cmets。

    这是一个有效的证明:http://ideone.com/FlccUJ

    【讨论】:

    • 另外,你可以看看这个:python.org/dev/peps/pep-0008/#maximum-line-length
    • @Yotam:实际上,请参阅我的回答中“根据 PEP8”文本附加的链接。另外,我的回答中的引用直接来自您在此处粘贴的内容。
    • 在这种情况下我们应该怎么做才能分割点? obj.method1(args1).method2(args2).method3(args3)
    • 不确定内联方式,但您可以使用a=obj.method1(args) # comm1 & b=obj.method2(args2) # comm2 等。
    • @lago-lito:在这种情况下,我也会使用括号将其拆分。如果您想评论每个片段,那么显然您仍然可以按照 PEP8 执行此操作:obj.method1( \n # Important method 1 \n args1 \n ).method2( \n # Importand other method \n args2 \n @ 987654334@ \n # Method that needs to be called last \n args3 \n )。也许它看起来太有表现力了,但是嘿 - 是你想要评论链中的每个方法;)
    【解决方案2】:

    不确定python是否支持您尝试执行的操作。阅读PEP8 section about inline comments。将 cmets 放在行延续的中间是“丑陋的”并且可能令人困惑。

    如果您想对某些内容进行 cmets 或对于内联 cmets 在 # 之后的所有内容,Python 方式是在每一行上使用 #

    如果你真的想评论一个真正需要的多行语句,把它放在它之前或之后。

    a, b, c, d = range(1, 5)
    # a is ..., b is ...
    # c is ..., d is ...
    result = (a, b, c, d)
    

    当然不想争论风格,但仅仅因为你可以做某事并不意味着它是明确的。内联 cmets 非常适合澄清只需要短指针的短代码行。

    【讨论】:

    • 好吧,PEP8 中引用的部分没有说明行延续中的 cmets。它说内联 cmets 很明显会分散注意力,但有时很有用。在这种情况下,我假设它们有用的。也可以注释多行语句(参见my answer)。标准是将块 cmets 放在 他们正在评论的东西之前 (source) - 当然这是关于 block cmets,而不是 inline cmets(显然必须在注释部分之后)。
    猜你喜欢
    • 2012-10-06
    • 1970-01-01
    • 2021-09-24
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多