Python 中的短路技術?


對於程式設計新手來說,一個常見的錯誤是對布林運算子工作方式的誤解,這源於 Python 直譯器讀取這些表示式的機制。例如,在最初學習“and”和“or”語句後,人們可能會假設表示式 X = (‘x’ or ‘y’) 會檢查變數 X 是否等效於字串 ‘a’ 或 ‘b’ 之一。事實並非如此。要理解我想要表達的意思,請啟動一個與直譯器的互動式會話並輸入以下表達式

>>> 'x' == ('x' or 'y')
True
>>> 'y' == ('x' or 'y')
False
>>> 'x' == ('x' and 'y')
False
>>> 'y' == ('x' and 'y')
True

此時,and 和 or 運算子似乎壞了。對於前兩個表示式,‘x’ 等效於 ‘x’ 或 ‘y’ 不是很合理。此外,‘y’ 等效於 ‘x’ 和 ‘y’ 也沒有任何意義。在檢查瞭解釋器如何處理布林運算子之後,這些結果實際上完全符合您的要求,只是與您認為自己所要求的不同。

對於 or 表示式,Python 直譯器首先獲取第一個語句並檢查其是否為真。當第一個語句為真時,Python 會返回該物件的返回值,而無需檢視第二個引數。這是因為對於 or 表示式,如果其中一個值為真,則整個表示式為真;並且程式不會檢視第二個語句。但是,如果第一個物件的返回值計算結果為假,則 Python 會檢查第二個語句並返回該值。由於前半部分為假,因此後半部分決定表示式的真值。直譯器這種“懶惰”的行為稱為“短路”,是許多程式語言中評估布林表示式的常用方法。

類似地,對於 and 表示式,Python 使用短路技術來加速真值評估。如果第一個語句為假,則整個表示式必須為假,它會返回該物件的返回值(假),否則,如果第一個值為真,它會檢查第二個值並返回該值。讓我們看一下直譯器在遍歷程式碼時“看到”的內容

第一種情況

'x' == ('x' or 'y') # Look at parentheses first, so evaluates "('x' or 'y")"
# 'x' is a nonempty string, so the first value is True
>>> 'x' == 'x' # the string 'x' is equivalent to the string 'x' , so our expression is True
True

第二種情況

'y' == ('x' or 'y')# Look at parentheses first, so evaluates expression "('x' or 'y')"
# 'x' is a nonempty string, so the first value is True
#Return that first value : 'x'
'y' == 'x'# the string 'y' is not equivalent to the string 'x', so the expression is False

第三種情況

>>> 'x' == ('x' and 'y')# Look at parentheses first, so evaluate expression "('x' and 'y')"
#'x' is a nonempty string, so the first value is True, examine second value
# 'y' is a nonempty string, so second value is True
#Return that second value as result of whole expression: 'y'
>>> 'x' == 'y'# the string 'x' is not equivalent to the string 'y', so expression is False
False

第四種情況

>>> 'y' == ('x' and 'y')# Look at parenthese first, so evaluates expression "('x' and 'y')"
True
# 'x' is a nonempty string, so the first value is True, examine second value
# 'y' is a nonempty string, so second value is True
# Return that second value as result of whole expression: 'y'
>>> 'y' == 'y'# the string 'y' is equivalent to the string 'y', so expression is True
True

短路求值意味著在評估 AND 和 OR 這樣的布林表示式時,一旦找到滿足或否定表示式的第一個條件,就可以停止。

官方文件中對短路的解釋

操作
結果
描述
x or y
如果 x 為假,則為 y,否則為 x
僅當第一個引數為假時才評估第二個引數(y)
x and y
如果 x 為假,則為 x,否則為 y
僅當第一個引數(x)為真時才評估第二個引數(y)
not x
如果 x 為假,則為真,否則為假
not 的優先順序低於非布林運算子

 

更新於: 2019-07-30

1K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.