pythonclassoopmagic-methodsobject-comparison

How to use dunder methods for object comparison


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:

  1. 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
  1. 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
  1. 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
  1. 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!


Solution

  • 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)

    class A:
        def __init__(self, n):
            self.n = n
    
        def __le__(self, other):
            return self.n <= other.n
    
    a = A(5)
    b = A(10)
    print(a <= b)
    

    will return True, because 5 is smaller-or-equal to 10.