拆分的长条件表达式线
问题描述:
我有一些if语句,如:拆分的长条件表达式线
def is_valid(self):
if (self.expires is None or datetime.now() < self.expires)
and (self.remains is None or self.remains > 0):
return True
return False
当我键入此表达式我的Vim自动移动and
新线与此相同的缩进if
线。我尝试更多的缩进组合,但验证总是说那是无效的语法。如何建立长期如果?
答
在整个条件下添加更多等级的括号。这将允许您根据需要插入换行符。
if (1+1==2
and 2 < 5 < 7
and 2 != 3):
print 'yay'
关于空间使用的实际数量,Python Style Guide不要求什么,但给出了一些建议:
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
答
把换行符括号内 if ((....) and (...)):
答
你可以反转测试并在测试的子集上返回False:
def is_valid(self):
if self.expires is not None and datetime.now() >= self.expires:
return False
if self.remains is not None and self.remains <= 0:
return False
return True
通过这种方式,您可以分解长测试线,并使整个事物更具可读性。
是的,你可以在你的布尔测试中使用额外的括号来允许测试中的换行符,但是当你必须跨越多行时,可读性会受到很大的影响。
只是一个评论,你没有必要在你的例子中有一个'if'语句。你可以'return(self.expires是None或datetime.now()...)' – mgilson 2012-07-30 14:01:33
我刚刚学习Python,我想我可以做到这一点,但没有那么好。谢谢mgilson – kbec 2012-07-30 14:07:21