0

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

9
  • 1
    return Adder(self.value + other.value + random.randrange(1, 6)) Commented May 9, 2021 at 19:38
  • I accidentally published the wrong question earlier. I have updated my question to the right one. Apologies for the confusion. @OlvinRoght Commented May 9, 2021 at 20:11
  • The code you posted says: "TypeError: __init__() missing 1 required positional argument: 'cost'" because Inventory(self.cost < other.cost) attempts to initialise an instance of Inventory providing self.cost < other.cost as item and nothing as cost. Commented May 9, 2021 at 20:14
  • Do i have to initialize item too something likeInventory(self.item + "," + str(self.cost) < str(other.cost))? @ForceBru Commented May 9, 2021 at 20:20
  • @hamtonko, why? __lt__(self, other) should answer the question: "Is self less than other? Yes or no?" So it should return a Boolean (True or False). There could be reasons to return something else, but I don't think it makes sense here Commented May 9, 2021 at 20:23

1 Answer 1

2

Replace your method with:

def __lt__(self, other):
    return self.cost < other.cost

inventory1 < inventory2 should return True or False for sorting to work, not an instance of Inventory.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.