我对python比较新,并且不太明白这里发生了什么。我有以下代码:
if cell.location != (always_empty_location
and random.random() < self.settings['OBSTACLE_RATIO']):
它已经坏了,但如果我删除括号并做一个简单的
and \
在第一行,它的工作原理。我似乎无法找到python如何处理这样的场景的可靠解释。网上的一切都表明这应该有用。
答案 0 :(得分:3)
这与换行符无关,只是
if a != b and c < d:
与
非常不同if a != (b and c < d):
第一个条件解析为(a != b) and (c < d)
,而第二个条件解析为a != (b and (c < d))
。
答案 1 :(得分:0)
在Python中,如果将其包装在paren中或使用\
,则只能执行多行条件。
这样可行:
if foo == 1 and \
bar == 2:
do_something()
这将有效:
if (foo == 1 and
bar == 2):
do_something()
然而,你所做的是在一半的条件下加上一个括号!
if foo == (1
and bar == 2):
do_something()
所以这里发生的是它正在评估(1 and bar == 2)
,然后测试foo
的值。如果foo == True
那么那就行了。但是,如果foo == False
和bar != 2
,那么它将通过。