2013-06-21 152 views
4

如果我有以下幾點:蟒蛇:訂單和執行

if a(my_var) and b(my_var): 
    do something 

我可以假設,如果a()Trueb()只計算?或者可能首先做b()

請求因爲評估b()將導致例外a()False

回答

1

隨着help()美妙的幫助(哈):

>>> help('and') 

Boolean operations 
****************** 

    or_test ::= and_test | or_test "or" and_test 
    and_test ::= not_test | and_test "and" not_test 
    not_test ::= comparison | "not" not_test 

... 

The expression ``x and y`` first evaluates *x*; if *x* is false, its 
value is returned; otherwise, *y* is evaluated and the resulting value 
is returned. 

... 

所以,是的,如果a(my_var)返回false,那麼函數b將不會被調用。

7

b()只有在a(my_var)True時纔會被評估,是的。如果a(my_var)錯誤,and運營商短路。

boolean operators documentation

表達x and y首先評估x;如果x爲假,則返回其值;否則,將評估y並返回結果值。

您可以用打印的東西函數調用時測試這個自己:

>>> def noisy(retval): 
...  print "Called, returning {!r}".format(retval) 
...  return retval 
... 
>>> noisy(True) and noisy('whatever') 
Called, returning True 
Called, returning 'whatever' 
'whatever' 
>>> noisy(False) and noisy('whatever') 
Called, returning False 
False 

的Python consideres空箱和數字0值假:

>>> noisy(0) and noisy('whatever') 
Called, returning 0 
0 
>>> noisy('') and noisy('whatever') 
Called, returning '' 
'' 
>>> noisy({}) and noisy('whatever') 
Called, returning {} 
{} 

自定義類可以實現__nonzero__ hook爲同一個測試返回一個布爾標誌,或者如果它們是一個容器類型,則實現一個__len__ hook;返回0表示容器是空的並被認爲是虛假的。

在密切相關的說明中,or運算符執行相同的操作,但相反。如果第一個表達式的計算結果爲真,則不會評估第二個表達式:

>>> noisy('Non-empty string is true') or noisy('whatever') 
Called, returning 'Non-empty string is true' 
'Non-empty string is true' 
>>> noisy('') or noisy('But an empty string is false') 
Called, returning '' 
Called, returning 'But an empty string is false' 
'But an empty string is false' 
1

是的,這樣做是安全的。如果對條件進行懶惰評估,那麼就是蟒蛇。

0

編譯器總是從上到下和從左到右讀取。所以If False and True然後編譯器首先遇到False,它退出if條件。這對我所知道的所有軟件都有效。