Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

object.__le__

Metoda definiuje relację mniejszy lub równy, która może opisywać również częściowy porządek.

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

Składnia

left <= right

Metoda definiuje relację mniejszy lub równy, która może opisywać również częściowy porządek.

object.__le__

Nie wynika automatycznie z metod dla < i == ani nie tworzy automatycznie <. Po NotImplemented można spróbować odbitego __ge__, z priorytetem ścisłego podtypu po prawej. Bez implementacji powstaje TypeError.

Zawieranie praw daje True True False, a osobne < zawodzi.

class Left:
    def __le__(self,other): return NotImplemented
class Right:
    def __ge__(self,other): return 'reflected'
assert (Left()<=Right())=='reflected'
try: Left()<=object()
except TypeError: pass
else: raise AssertionError

Przykłady

class Rights:
    def __init__(self, names): self.names = set(names)
    def __le__(self, other):
        if not isinstance(other, Rights): return NotImplemented
        return self.names <= other.names
a, b = Rights(["read"]), Rights(["read","write"])
print(a <= a, a <= b, b <= a)
try: a < b
except TypeError as exc: print(type(exc).__name__)

Wynik

True True False
TypeError

Zawieranie praw daje True True False, a osobne < zawodzi.

Źródła