2017-07-14 142 views
-1

我想實現一個類的重載,並得出結論,如果一個給定的時間點例如12:59:50事件發生在另一個事件之前,所以輸出是真或假,只是一個簡單的比較測試。正如你所看到的那樣,我實現了它,但是,我非常肯定,這不是最棘手或更好說的,反對導向的方法來執行任務。我是python新手,所以有什麼改進嗎?multistep比較測試蟒蛇

由於

def __lt__(self, other): 
    if self.hour < other.hour: 
     return True 

    elif (self.hour == other.hour) and (self.minute < other.minute):    
     return True 

    elif (self.hour == other.hour) and (self.minute == other.minute) and (self.second < other.second):    
     return True 

    else:    
     return False 
+0

你可以使用'datetime' –

回答

2

元組(和其他序列)已經執行字典比較的類型要實現:

def __lt__(self, other): 
    return (self.hour, self.minute, self.second) < (other.hour, other.minute, other.second) 

operator模塊可以清理一下一點:

from operator import attrgetter 

def __lt__(self, other): 
    hms = attrgetter("hour", "minute", "second") 
    return hms(self) < hms(other)