Python - 短路的奇怪行为

Hid*_*den 3 python short-circuiting

在下面的代码片段中,函数f按预期执行:

def f():
  print('hi')
f() and False
#Output: 'hi'
Run Code Online (Sandbox Code Playgroud)

但是在下面的类似代码片段a中没有增加:

a=0
a+=1 and False
a
#Output: 0
Run Code Online (Sandbox Code Playgroud)

但是如果我们用True而不是False的ashortcircuit增加:

a=0
a+=1 and True
a
#Output: 1
Run Code Online (Sandbox Code Playgroud)

短路是如何以这种方式运行的?

Max*_*oel 8

那是因为f() and False是一个表达式(技术上是一个单表达式语句),a += 1 and False而是一个赋值语句.它实际上解析为a += (1 and False),并且因为1 and False等于False并且False实际上是整数0,所以发生的是a += 0无操作.

(1 and True)然而,评估为True(整数1),所以a += 1 and True意味着a += 1.

(还要注意Python的and并且or总是返回可以明确确定操作结果的第一个操作数)