Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

functools.total_ordering

Uzupełnia brakujące porównania porządkowe na podstawie jednej metody porządkującej, takiej jak `__lt__`, oraz zgodnej z nią metody równości `__eq__`.

Wersja: Python 3.14; repository image, production runtime not attested

Składnia

@functools.total_ordering

Uzupełnia brakujące porównania porządkowe na podstawie jednej metody porządkującej, takiej jak __lt__, oraz zgodnej z nią metody równości __eq__.

Wygenerowana metoda wywołuje zdefiniowane porównania, co oznacza dodatkowe wywołania i dłuższy stos niż przy ręcznej implementacji wszystkich sześciu metod. Nie nadpisuje już istniejących metod, także odziedziczonych. Zwrócenie NotImplemented dla obcego typu umożliwia porównanie odbite lub TypeError.

Równe rangi spełniają >=, a ranga 1 nie przewyższa 3.

from functools import total_ordering
@total_ordering
class Level:
    def __init__(self, n): self.n = n
    def __eq__(self, other): return self.n == other.n if isinstance(other, Level) else NotImplemented
    def __lt__(self, other): return self.n < other.n if isinstance(other, Level) else NotImplemented
assert Level(2) >= Level(2) and Level(3) > Level(2)
try:
    Level(1) < 2
except TypeError:
    pass
else:
    raise AssertionError
assert Level.__lt__(Level(2), "x") is NotImplemented

Przykłady

import functools
@functools.total_ordering
class Rank:
    def __init__(self, value): self.value = value
    def __eq__(self, other): return self.value == other.value if isinstance(other, Rank) else NotImplemented
    def __lt__(self, other): return self.value < other.value if isinstance(other, Rank) else NotImplemented

print(Rank(2) >= Rank(2), Rank(1) > Rank(3))

Wynik

True False

Równe rangi spełniają >=, a ranga 1 nie przewyższa 3.

Źródła