[英]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
等於False
而False
實際上是整數0,所以發生的是a += 0
,即無操作。
(1 and True)
但是,計算結果為True
(整數1),因此a += 1 and True
表示a += 1
。
(還要注意Python的and
和or
總是返回可以明確確定操作結果的第一個操作數)
我相信
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.