Search code examples
pythoncomparisonmagic-methods

Python magic method confusion


I've run into some confusing behaviour of the magic comparison methods. Suppose we have the following class:

class MutNum(object):
    def __init__ (self, val):
        self.val = val

    def setVal(self, newval):
        self.val = newval

    def __str__(self):
        return str(self.val)

    def __repr__(self):
        return str(self.val)

    # methods for comparison with a regular int or float:
    def __eq__(self, other):
        return self.val == other

    def __gt__(self, other):
        return self.val > other

    def __lt__(self, other):
        return self.val < other

    def __ge__(self, other):
        return self.__gt__(other) or self.__eq__(other)

    def __le__(self, other):
        return self.__lt__(other) or self.__eq__(other)

The class does what it is supposed to do, comparing a MutNum object to a regular int or float is no problem. However, and this is what I don't understand, it even compares fine when the magic methods are given two MutNum objects.

a = MutNum(42)
b = MutNum(3)
print(a > b) # True
print(a >= b) # True
print(a < b) # False
print(a <= b) # False
print(a == b) # False

Why does this work? Thanks.


Solution

  • It evaluates as follows (using a repr-like notation instead of referring to variables):

       MutNum(42) > MutNum(3)
    => MutNum(42).__gt__(MutNum(3))
    => MutNum(42).val > MutNum(3)
    => 42 > MutNum(3)
    

    And from there, it's just the int-MutNum comparision you already know works.