CKTIS / Python
object.__eq__
Metoda równości może porównać własne dane lub zwrócić NotImplemented dla nieobsługiwanego typu.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
left == rightMetoda równości może porównać własne dane lub zwrócić NotImplemented dla nieobsługiwanego typu.
object.__eq__
Python może wtedy spróbować drugiego operandu, a po dwóch odmowach == porównuje tożsamość. W zwykłej klasie nadpisanie równości bez własnego haszu wyłącza haszowanie.
Etykiety AA i aa są równe, napis aa nie jest etykietą, a hash zgłasza TypeError.
a,b=object(),object()
assert object.__eq__(a,a) is True and object.__eq__(a,b) is NotImplemented
assert (a==b) is False
class Other:
def __eq__(self,other): return True
assert a==Other()
Przykłady
class Label:
def __init__(self, name): self.name = name
def __eq__(self, other):
if not isinstance(other, Label): return NotImplemented
return self.name.casefold() == other.name.casefold()
print(Label("AA") == Label("aa"), Label("AA") == "aa")
try: hash(Label("a"))
except TypeError as exc: print(type(exc).__name__)
Wynik
True False TypeError
Etykiety AA i aa są równe, napis aa nie jest etykietą, a hash zgłasza TypeError.