Patryk
Patryk

Reputation: 13

Cannot implement __lt__ operator

I have a class Quantity and I want to implement the __lt__ operator to overload. I have implemented the method as shown below.

    def __lt__(self, other):
        if isinstance(other, Quantity):
            return other.value < self.value
        if isinstance(other, numbers.Real):
            return self.value < other
        raise NotImplemented

When I import it into the python console and try to execute it

>>> Quantity(1.2) > 1

I get the following error

AttributeError: 'int' object has no attribute 'number'

And if I try to execute it like this

>>> Quantity(1.2) < 1

I get the following error

TypeError: '<' not supported between instances of 'Quantity' and 'int'

Does anyone know how can I implement the overload to work with < and >?

Update

Here is the full class

class Quantity:

    def __init__(self, value):
        self.value = float(value)

    def __float__(self):
        return self.value

    def __repr__(self):
        return 'Quantity({})'.format(self.value)

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


   def __lt__(self, other):
        if isinstance(other, Quantity):
            return other.value < self.value
        if isinstance(other, numbers.Real):
            return self.value > other
        raise NotImplemented

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        value = round(value, 10)
        self._value = int(value * 1000) / 1000.0

Upvotes: 0

Views: 1232

Answers (1)

dspencer
dspencer

Reputation: 4481

You get an error on Quantity(1.2) > 1 because you have not defined __gt__ for your Quantity class. As pointed out, you also have an error in your __lt__ method and perform the comparison the wrong way around (other.value < self.value rather than self.value < other.value). I believe this should work:

def __lt__(self, other):                                                    
    if isinstance(other, Quantity):                                         
        return self.value < other.value                                     
    if isinstance(other, numbers.Real):                                     
        return self.value < other                                           
    raise NotImplemented                                                    

def __gt__(self, other):                                                    
    if isinstance(other, Quantity):                                         
        return self.value > other.value                                     
    if isinstance(other, numbers.Real):                                     
        return self.value > other                                           
    raise NotImplemented

Your second example, Quantity(1.2) < 1 should work. The error message you quote on that one is not reproducible, it seems (I checked python 2.7 and 3.8).

Upvotes: 1

Related Questions