-1

我想实现一个类重载并得出结论,如果一个给定时间点的事件(例如 12:59:50)发生在另一个事件之前,所以输出是真还是假,只是一个简单的比较测试。如您所见,我实现了它,但是,我很确定这不是执行任务的最 Python 或更好的面向对象的方法。我是 python 新手,所以有什么改进吗?

谢谢

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
4

1 回答 1

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)
于 2017-07-14T15:44:40.037 回答