More magical methods reflected

I need the more-than-reflected magic method, and it doesn't seem to exist. Here's the situation. I have a class that keeps track of units. This is the property of the call. I have a magic method to handle comparisons, but it doesn't work when I put the property on the right. Here's 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)
        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 does a float> Property that uses the inline> not> which I defined with magic methods. I need a magic method to be used when the property is on the right. Isn't that so? If not, how can I write this so that any combination of values ​​and my own class can be compared. I would not like to have any rules for comparisons. IE, I don't want to just never be able to compare floats to property.


source to share

3 answers

You can use decorators to create the missing comparison methods for you: functools.total_ordering

import functools

class Property():


Then you will get False, False, False. Be sure to read its documentation.




is analogous __gt__

; you need to implement __lt__

. While you're at it, you should probably implement __le__

and __ge__




Since you have declared a method __float__()

, you can always write it as:

print float(y) > float(x)




All Articles