簡體   English   中英

Python - 短路的奇怪行為

[英]Python - Shortcircuiting strange behaviour

在下面的代碼片段中,函數f按預期執行:

def f():
  print('hi')
f() and False
#Output: 'hi'

但是在下面的類似代碼片段中, a不會增加:

a=0
a+=1 and False
a
#Output: 0

但是,如果我們用真帶有短路假的,而不是a被遞增:

a=0
a+=1 and True
a
#Output: 1

短路是如何以這種方式運行的?

那是因為f() and False是一個表達式(技術上是單表達式語句),而a += 1 and False是賦值語句。 它實際上解析為a += (1 and False) ,並且因為1 and False等於FalseFalse實際上是整數0,所以發生的是a += 0 ,即無操作。

(1 and True)但是,計算結果為True (整數1),因此a += 1 and True表示a += 1

(還要注意Python的andor總是返回可以明確確定操作結果的第一個操作數)

我相信

a+=1 and False

相當於

a+=(1 and False)

a+=1 and True

相當於

a+=(1 and True)

例如:

In [15]: a = 0

In [16]: a+=2 and True

In [17]: a
Out[17]: 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM