我有一长串代码,我希望在多行之间分解。我使用什么,语法是什么?
例如,添加一串字符串,
e= 'a' + 'b' + 'c' + 'd'
并将它分成两行:
e= 'a' + 'b' +
'c' + 'd'
什么是线?你可以在下一行有参数而没有任何问题:
a=dostuff(blahblah1,blahblah2,blahblah3,blahblah4,blahblah5,blahblah6,blahblah7)
否则你可以这样做:
ifa== True and\
b== False
查看样式指南以获取更多信息。
从您的示例行:
a= '1' + '2' + '3' +\'4' + '5'
要么:
a= ('1' + '2' + '3' +
'4' + '5')
请注意,样式指南表示使用括号的隐式延续是首选,但在这种特殊情况下,只是在表达式周围添加括号可能是错误的方法。
包装长行的首选方法是在括号,括号和括号内使用Python隐含的行继续。通过在括号中包装表达式,可以在多行上分割长行。这些应该优先使用反斜杠来继续行。
反斜杠有时可能仍然合适。例如,long,多个with语句不能使用隐式延续,因此可以接受反斜杠:
withopen('/path/to/some/file/you/want/to/read') asfile_1,\
open('/path/to/some/file/being/written', 'w') asfile_2:file_2.write(file_1.read())
另一个这样的情况是使用断言语句。
确保适当地缩进续行。打破二元运算符的首选位置是运算符之后,而不是它之前。一些例子:
class Rectangle(Blob):
def__init__(self,width,height,color='black',emphasis=None,highlight=0):
if (width== 0 andheight== 0 andcolor== 'red' andemphasis== 'strong' orhighlight> 100):
raise ValueError("sorry, you lose")
ifwidth== 0 andheight== 0 and (color== 'red' oremphasisis 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在他的计算机和排版系列中解释了传统规则:“虽然段落中的公式总是在二元操作和关系之后中断,但显示的公式总是在二元操作之前中断”[3]。
遵循数学传统通常会产生更易读的代码:
# Yes: easy to match operators with operandsincome= (gross_wages+taxable_interest+ (dividends-qualified_dividends)
-ira_deduction-student_loan_interest)
在Python代码中,只要约定在本地一致,就允许在二元运算符之前或之后中断。对于新代码,建议使用Knuth的样式。
[3]:Donald Knuth的The TeXBook,第195和196页