tim*_*geb 6 python comparison magic-methods
我遇到了魔术比较方法的一些令人困惑的行为.假设我们有以下课程:
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)
Run Code Online (Sandbox Code Playgroud)
该类执行它应该做的事情,将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
Run Code Online (Sandbox Code Playgroud)
为什么这样做?谢谢.
小智 5
评估结果如下(使用repr-like表示法而不是引用变量):
MutNum(42) > MutNum(3)
=> MutNum(42).__gt__(MutNum(3))
=> MutNum(42).val > MutNum(3)
=> 42 > MutNum(3)
Run Code Online (Sandbox Code Playgroud)
从那里开始,这只是您已经知道有效的int-MutNum比较。
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |