我在Python中有一个很长的if语句。什么是将其分成几行的最佳方法?我认为最具可读性/普通性。
答案 0 :(得分:143)
根据PEP8,长行应放在括号中。使用括号时,可以在不使用反斜杠的情况下拆分行。您还应该尝试在布尔运算符之后放置换行符。
除此之外,如果您使用代码样式检查(例如pycodestyle),则下一个逻辑行需要对代码块进行不同的缩进。
例如:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
答案 1 :(得分:35)
以下是PEP 8关于限制线长度的示例:
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)