Harley Holco..
679
您不需要在第二个条件行上使用4个空格.也许用:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
另外,不要忘记空格比您想象的更灵活:
if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
但这两个都相当难看.
也许会丢失括号(虽然风格指南不鼓励这样)?
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
这至少给你一些区别.
甚至:
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
我想我更喜欢:
if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
这是样式指南,(自2010年起)建议使用括号.
请注意,PEP 8不推荐使用尾随\解决方案.一个原因是,如果在编辑器中未显示空格而错误地添加空格,并且代码在语法上会变得不正确. (40认同)
这是错误的,样式指南说"通过在括号中包装表达式,可以在多行中分解长行.这些应该优先使用反斜杠来表示行继续." 你可以在这里看到:http://www.python.org/dev/peps/pep-0008/#maximum-line-length (14认同)
@joshcartme PEP在http://hg.python.org/peps/rev/7a48207aaab6更改为明确阻止反斜杠.我会更新答案. (8认同)
谢谢,更新您的示例可能是一个好主意,因为现在不推荐它们.我试图自己解决这个问题,并且对你的答案和风格指南(因此我的评论)之间的差异感到困惑.我不仅仅是想要迂腐. (3认同)
[PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-binary-operator)现在不鼓励在`还有`和`if`。 (3认同)