hamtonko
hamtonko

Reputation: 49

Sort with operator overloading in python

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

Upvotes: 0

Views: 1179

Answers (1)

Jasmijn
Jasmijn

Reputation: 10452

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.

Upvotes: 2

Related Questions