我有很长的一行代码,我想在多行中分手。我使用什么语法?
例如,添加一堆字符串,
e = 'a' + 'b' + 'c' + 'd'
把它分成两行:
e = 'a' + 'b' +
'c' + 'd'
线是什么?你可以在下一行有参数,没有任何问题:
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
否则,你可以做这样的事情:
if a == True and
b == False
请查阅风格指南,以取得更多资讯。
从您的示例行:
a = '1' + '2' + '3' +
'4' + '5'
或者:
a = ('1' + '2' + '3' +
'4' + '5')
请注意,风格指南指出,使用带括号的隐式连续是首选,但在这种情况下,只需在表达式中添加括号可能是错误的方法。
The preferred way of wrapping long lines is by using Python’s implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
>
Backslashes may still be appropriate at times. For example, long, multiple
with-statements cannot use implicit continuation, so backslashes are
acceptable:
with open('/path/to/some/file/you/want/to/read') as file_1,
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
Another such case is with assert statements.
>
Make sure to indent the continued line appropriately. The preferred place to
break around a binary operator is after the operator, not before it. Some
examples:
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
编辑:PEP8现在推荐数学家和他们的出版商使用 相反的惯例 (打破在二进制操作)提高可读性。
唐纳德·克努斯(Donald Knuth)的风格是在二元运算符之前打破 **垂直运算符,从而在确定哪些项目被添加和减去时减少了眼睛的工作量。
Donald Knuth explains the traditional rule in his Computers and Typesetting
series: “Although formulas within a paragraph always break after binary
operations and relations, displayed formulas always break before binary
operations”[3].
>
Following the tradition from mathematics usually results in more readable
code:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
In Python code, it is permissible to break before or after a binary
operator, as long as the convention is consistent locally. For new code
Knuth’s style is suggested.
[3]:Donald Knuth的The TeXBook,195和196页
未经作者同意,本文严禁转载,违者必究!