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)

该类完成了应做的事情,将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

为什么这样做?谢谢。

用户395760

评估结果如下(使用repr-like表示法而不是引用变量):

   MutNum(42) > MutNum(3)
=> MutNum(42).__gt__(MutNum(3))
=> MutNum(42).val > MutNum(3)
=> 42 > MutNum(3)

从那里开始,这只是您已经知道有效的int-MutNum比较。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章