Wpadłem w mylące zachowanie magicznych metod porównywania. Załóżmy, że mamy następujące klasy:Python magic method confusion
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)
Klasa robi to, co ma robić, porównując obiekt MutNum do regularnego int lub pływaka nie jest problemem. Jednak to jest to, czego nie rozumiem, nawet porównuje dobrze, gdy magiczne metody otrzymują dwa obiekty 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
Dlaczego to działa? Dzięki.
To może pomóc myśleć o '__gt__' i' __lt__' stojących w tej samej relacji co '__add__' i' __radd__', na przykład. Jeśli pierwszy nie ma zastosowania, Python próbuje drugi z odwróconymi operandami. – chepner