Python:反斜杠后的'#'评论

Mar*_*zyk 43 python format comments multiline backslash

这不起作用:

something = \
    line_of_code * \    #  Comment
    another_line_of_code * \    #  Comment
    and_another_one * \         #  Comment
    etc
Run Code Online (Sandbox Code Playgroud)

这也不是:

something = \
    #  Comment \
    line_of_code * \
    #  Comment \
    another_line_of_code * ...
Run Code Online (Sandbox Code Playgroud)

这也不是:

something = \
    ''' Comment ''' \
    line_of_code * \
    ''' Comment ''' \
    another_line_of_code * ...
Run Code Online (Sandbox Code Playgroud)

如果有一种方法可以将代码中的注释分成多行?

Tad*_*eck 43

这样做:

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
)
Run Code Online (Sandbox Code Playgroud)

实际上,根据PEP8,当将某些东西分成多行时,括号优先于斜杠:

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

在你的情况下,它也允许发表评论.

这是一个证据,它的工作原理:http://ideone.com/FlccUJ

  • 在这种情况下,我们应该做些什么来分割点?`obj.method1(args1).method2(args2).method3(args3)` (7认同)
  • @lago-lito:在这种情况下,我也会使用括号将其分开。如果你想注释每个段,那么显然你仍然可以按照 PEP8 执行此操作: `obj.method1(` \n `# 重要方法 1` \n `args1` \n `).method2(` \n `# importand other method` \n `args2` \n `).method3(` \n `# 最后需要调用的方法` \n `args3` \n `)`。也许它看起来太富有表现力,但是嘿 - 是你想要评论链中的每个方法;) (3认同)