我遇到了魔术比较方法的一些令人困惑的行为。假设我们有以下类:
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)
该类做了它应该做的事情,将 MutNum 对象与常规 int 或 float 进行比较是没有问题的。然而,这是我不明白的,当魔术方法被赋予两个 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
为什么这行得通?谢谢。