2013-09-25 213 views
1

我應該如何解釋Python中的這句話(根據運算符優先級)?Python運算符優先級

c = not a == 7 and b == 7 

c = not (a == 7 and b == 7)c = (not a) == 7 and b == 7

感謝

+2

http://docs.python.org/2/reference/expressions.html#operator-precedence – George

回答

5

使用dis模塊:

>>> import dis 
>>> def func(): 
...  c = not a == 7 and b == 7 
...  
>>> dis.dis(func) 
    2   0 LOAD_GLOBAL    0 (a) 
       3 LOAD_CONST    1 (7) 
       6 COMPARE_OP    2 (==) 
       9 UNARY_NOT   
      10 JUMP_IF_FALSE_OR_POP 22 
      13 LOAD_GLOBAL    1 (b) 
      16 LOAD_CONST    1 (7) 
      19 COMPARE_OP    2 (==) 
     >> 22 STORE_FAST    0 (c) 
      25 LOAD_CONST    0 (None) 
      28 RETURN_VALUE 

所以,它看起來像:

c = (not(a == 7)) and (b == 7) 
2

按照documentation的順序,從最低優先級(最低結合),以最高優先(最具約束力):

  1. and
  2. not
  3. ==

所以表達式not a == 7 and b == 7將這樣的評價:

((not (a == 7)) and (b == 7)) 
^ ^ ^ ^
second first third first 

換句話說,評估樹看起來就像這樣:

 and 
    / \ 
    not == 
    | /\ 
    == b 7 
/\ 
    a 7 

最後完成的事情是將表達式的值賦值給c

+1

您給出的鏈接表示該列表按最低優先級排序,因此它會是'(not(a == 7))和(b == 7)''。如果它是從最高到最低,就像你說的那樣,那麼它將是'((不是a)==(7和b))== 7',因爲'和'會比'=='更高的優先級。 –

+0

@EricFinn是的,我的錯誤 - 修好了! –