Comparing two objects using dunder methods
I was trying to compare two 'Time objects', but I got this error:
'TypeError: '<' not supported between instances of 'Time' and 'Time'
This is what I tried:
- I First initialized the 'time Class'.
class Time:
def __init__(self, h, m, s):
self._h = h
self._m = m
self._s = s
# Read-only field accessors
@property
def hours(self):
return self._h
@property
def minutes(self):
return self._m
@property
def seconds(self):
return self._s
- I created a method to compare the two Time objects.
def _cmp(time1, time2):
if time1._h < time2._h:
return 1
if time1._h > time2._h:
return -1
if time1._m < time2._m:
return 1
if time1._m > time2._m:
return -1
if time1._s < time2._s:
return 1
if time1._s > time2._s:
return -1
else:
return 0
- I created the dunder methods.
def __eq__(self, other):
return True if _cmp(self, other) == 0 else False
def __lt__(self, other):
return True if _cmp(self, other) == 1 else False
def __le__(self, other):
return True if _cmp(self, other) == 1 or _cmp(self, other) == 0 else False
- I instantiated some objects, and tried comparing them (resulting in an error).
t1 = Time(13, 10, 5)
t2 = Time(5, 15, 30)
print(t1 < t2)
print(t2 <= t1)
I must surely be missing something. All tips on coding are welcome!
There are many dunder-methods (or magic-methods), if you want to use
<and<=then you want to use__lt__for<and__le__for<=(stands for less-than and less-equal)will return True, because 5 is smaller-or-equal to 10.