Search code examples
pythonmagic-methods

reflected greater than magic methods


I am in need of a reflected magic method "greater than" and there does not appear to be one. Here is the situation. I have a class which keeps track of units. It is call Property. I have the magic method setup to handle comparisons, but it does not work when I put the Property on the right side. Here is an example:

class Property():
def __init__(self, input, units):
    self.value = input
    self.units = units


def __gt__(self, other):
    if isinstance(other, Property):
        return self.value.__gt__(other.value)
    else:
        return self.value.__gt__(other)

def __float__(self):
    return float(self.value)

if __name__=='__main__':

    x = Property(1.,'kg')
    y = Property(0.,'kg')
    print y > x
    print float(y) > x
    print y > float(x)

So if you run this you will see the output is: False, True, False because the middle example is executing float > Property which uses the built in > not the > I have defined using magic methods. I need a magic method that will be used when the Property is on the right hand side. Is that not a thing? If not, how can I write this so that any combination of values and my own class can be compared. I would like to not have any rules for comparisons. IE, I don't want to just never be able to compare a float to a property.


Solution

  • You can use a functools.total_ordering decorator to create the missing comparison methods for you:

    import functools
    
    @functools.total_ordering
    class Property():
        ...
    

    Then you get False, False, False. Do make sure to read its documentation, though.