我遇到了魔术比较方法的一些令人困惑的行为。 假设我们有以下类:
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
为什么会这样?谢谢。
最佳答案
它的计算如下(使用类似 repr
的符号而不是引用变量):
MutNum(42) > MutNum(3)
=> MutNum(42).__gt__(MutNum(3))
=> MutNum(42).val > MutNum(3)
=> 42 > MutNum(3)
从那里开始,这就是您已经知道有效的 int-MutNum 比较。
关于Python魔术方法混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19731048/