2013-06-19 80 views

回答

14

內部,它作爲a < b and b < c處理,所以你需要重載只__lt____gt__

docs

X <Ÿ< = z是等價於x < y和y < = z,除了y是 只評估一次(但是在兩種情況下,當 x < y被發現是錯誤時根本不評估z)。

>>> import dis 
>>> dis.dis(lambda : a < b < c) 
    1   0 LOAD_GLOBAL    0 (a) 
       3 LOAD_GLOBAL    1 (b) 
       6 DUP_TOP    
       7 ROT_THREE   
       8 COMPARE_OP    0 (<) 
      11 JUMP_IF_FALSE_OR_POP 21 
      14 LOAD_GLOBAL    2 (c) 
      17 COMPARE_OP    0 (<) 
      20 RETURN_VALUE   
     >> 21 ROT_TWO    
      22 POP_TOP    
      23 RETURN_VALUE 

演示:

class A(object): 
    def __lt__(self, other): 
     print 'inside lt' 
     return True 
    def __gt__(self, other): 
     print 'inside gt' 
     return True 
...   
>>> a = A() 
>>> 10 < a < 20 
inside gt 
inside lt 
True