多步骤比较测试python
我想实现一个类重载,并得出结论,如果一个事件在给定的时间点(例如12:59:50)发生在另一个事件之前,那么输出是真是假,这只是一个简单的比较测试。正如您所看到的,我实现了它,但是,我非常确定这不是执行任务的最具python风格或更好的方法,也就是说,面向对象的方法。我是python新手,有什么改进吗 谢谢多步骤比较测试python,python,if-statement,comparison,multi-step,Python,If Statement,Comparison,Multi Step,我想实现一个类重载,并得出结论,如果一个事件在给定的时间点(例如12:59:50)发生在另一个事件之前,那么输出是真是假,这只是一个简单的比较测试。正如您所看到的,我实现了它,但是,我非常确定这不是执行任务的最具python风格或更好的方法,也就是说,面向对象的方法。我是python新手,有什么改进吗 谢谢 def __lt__(self, other): if self.hour < other.hour: return True elif (self
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
元组和其他序列已执行您正在实现的词典比较类型:
def __lt__(self, other):
return (self.hour, self.minute, self.second) < (other.hour, other.minute, other.second)
你可以用datetime
from operator import attrgetter
def __lt__(self, other):
hms = attrgetter("hour", "minute", "second")
return hms(self) < hms(other)