Mi sono imbattuto in un comportamento confuso dei metodi di confronto magico. Supponiamo di avere la seguente classe:Confusione di metodi magici in Python
class MutNum(object):
def __init__ (self, val):
self.val = val
def setVal(self, newval):
self.val = newval
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
# methods for comparison with a regular int or float:
def __eq__(self, other):
return self.val == other
def __gt__(self, other):
return self.val > other
def __lt__(self, other):
return self.val < other
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
La classe fa quello che deve fare, mettendo a confronto un oggetto MutNum ad un normale float int o non è un problema. Tuttavia, e questo è ciò che non capisco, è paragonabile anche quando i metodi magici ricevono due oggetti MutNum.
a = MutNum(42)
b = MutNum(3)
print(a > b) # True
print(a >= b) # True
print(a < b) # False
print(a <= b) # False
print(a == b) # False
Perché funziona? Grazie.
Potrebbe essere utile pensare a '__gt__' e' __lt__' nella stessa relazione di '__add__' e' __radd__', ad esempio. Se il primo non si applica, Python prova l'altro con gli operandi invertiti. – chepner