CKTIS / Python
object.__eq__
Un metodo di uguaglianza può confrontare i dati o restituire NotImplemented per un tipo non supportato.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
left == rightUn metodo di uguaglianza può confrontare i dati o restituire NotImplemented per un tipo non supportato.
object.__eq__
Python può allora provare l’altro operando e usa l’identità dopo due rifiuti. In una classe ordinaria ridefinire l’uguaglianza senza definire l’hash disabilita l’hashing.
Le etichette AA e aa sono uguali, la stringa no e hash solleva 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()
Esempi
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__)
Risultato
True False TypeError
Le etichette AA e aa sono uguali, la stringa no e hash solleva TypeError.