I wanna implement a class overloading and conclude if an event with a given point of time for example 12:59:50 happens before another event so the output is true or false, just a simple comparison test. I implemented it, as you can see, but, i'm pretty much sure this is not the most pythonic or better to say, objected oriented approach to carry out the tasks. I'm new to python so is there any improvement out there ?
Thanks
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
Tuples (and other sequences) already perform the type of lexicographic comparison you are implementing:
def __lt__(self, other):
return (self.hour, self.minute, self.second) < (other.hour, other.minute, other.second)
The operator
module can clean that up a little:
from operator import attrgetter
def __lt__(self, other):
hms = attrgetter("hour", "minute", "second")
return hms(self) < hms(other)