Python Glossary Русский

all Python 3OOPfunction

__lt__

magic methods

The method behind <. On its own it is enough for sorted() and min() to order objects.

Syntax

def __lt__(self, other): ...

sorted, min and heapq compare only with <, so __lt__ alone is enough for sorting; max compares with >, yet __lt__ alone suffices there too: for a > b without __gt__ Python tries the reflected b < a. The operators <= and >= are not derived from __lt__ — functools.total_ordering supplies them from __eq__ and one comparison.

Examples

class Version:
    def __init__(self, major, minor):
        self.v = (major, minor)
    def __lt__(self, other):
        return self.v < other.v
    def __repr__(self):
        return f'{self.v[0]}.{self.v[1]}'
print(sorted([Version(3, 12), Version(3, 9), Version(3, 11)]))  # → [3.9, 3.11, 3.12]
print(Version(3, 9) > Version(3, 8))  # → True — отражённое Version(3, 8) < Version(3, 9)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy