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
Quantity? What arenumbers? Also, your firstifstatement will returnTrueifself.valueis greater thanother.value