bhylu.com

Advertisements

__lt__

__lt__ defines the less-than relationship used by ordering operations. For simple one-off sorting, a key function is often clearer.

Understand the idea

A custom ordering should be consistent across the values it supports. Return NotImplemented for unrelated operands. Ties need a policy: compare only price when equal-price items should be equivalent for ordering, or compare a documented tuple of fields when a deterministic tie-breaker belongs in the type's ordering contract.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Offer:
    def __init__(self, cents):
        self.cents = cents
    def __lt__(self, other):
        if not isinstance(other, Offer):
            return NotImplemented
        return self.cents < other.cents

print(Offer(250) < Offer(450))

Read the result

The result is True because 250 is less than 450.

Try one change

Compare custom ordering with sorted(records, key=...) and explain which choice keeps a local report simpler.