I am new to operator overloading so please bear with me. I have a class with operator overloading __lt__ which is supposed to prints out the sorted result of a list but I'm getting error '<' not supported between instances of 'Inventory' and 'Inventory'. Why can't the sort method sort the contents of the list. Where did I go wrong? Any help is appreciated. Thanks in advance.
class Inventory:
def __init__(self, item, cost):
self.item = item
self.cost = cost
def __str__(self):
return "{:16s} ${:6.2f}".format(self.item, self.cost)
def __lt__(self, other):
return Inventory(self.cost < other.cost)
i1 = Inventory("Pentel Pen", 1.45)
i2 = Inventory("Ruler", .99)
i3 = Inventory("Calculus Text", 245.99)
i4 = Inventory("Diet Coke", 1.80)
t = [i1, i2, i3, i4]
t = [i1, i2, i3, i4]
for i in sorted(t):
print(i)
Expected result:
Ruler $ 0.99
Pentel Pen $ 1.45
Diet Coke $ 1.80
Calculus Text $245.99
return Adder(self.value + other.value + random.randrange(1, 6))__init__()missing 1 required positional argument: 'cost'" becauseInventory(self.cost < other.cost)attempts to initialise an instance ofInventoryprovidingself.cost < other.costasitemand nothing ascost.Inventory(self.item + "," + str(self.cost) < str(other.cost))? @ForceBru__lt__(self, other)should answer the question: "Isselfless thanother? Yes or no?" So it should return a Boolean (TrueorFalse). There could be reasons to return something else, but I don't think it makes sense here