如何在自己的类上重写或执行 python 中的最小/最大?

use*_*317 0 python max min

不确定标题这个问题的最佳方式,但是我如何覆盖或执行min(a, b)max(a, b)制作的类的对象?我可以像下面一样覆盖gt和 lt 但我想覆盖最小值或最大值,以便我能够使用类似max(a, b, c ,d). 该类也将有多个属性,但我认为对于这个例子来说 2 个就足够了。

class MyClass:
    def __init__(self, item1, item2):
        self.item1 = item1
        self.item2 = item2

    def __gt__(self, other):
        if isinstance(other, MyClass):
            if self.item1 > other.item1:
                return True
            elif self.item1 <= other.item1:
                return False
            elif self.item2 > other.item2:
                return True
            elif self.item2 <= other.item2:
                return False

    def __lt__(self, other):
        if isinstance(other, MyClass):
            if self.item1 < other.item1:
                return True
            elif self.item1 >= other.item1:
                return False
            elif self.item2 < other.item2:
                return True
            elif self.item2 >= other.item2:
                return False
Run Code Online (Sandbox Code Playgroud)

前任:

a = MyClass(2,3)
b = MyClass(3,3)

print(a > b)
# False
Run Code Online (Sandbox Code Playgroud)

我尝试覆盖,__cmp__但这似乎不起作用。

希望能够执行max(a, b)并返回b对象

小智 5

只需重写比较魔术方法即可。

class A(object):

    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        return self.value < other.value

    def __le__(self, other):
        return self.value <= other.value

    def __eq__(self, other):
        return self.value == other.value

    def __ne__(self, other):
        return self.value != other.value

    def __gt__(self, other):
        return self.value > other.value

    def __ge__(self, other):
        return self.value >= other.value

    def __str__(self):
        return str(self.value)

a = A(10)
b = A(20)
min(a, b)
Run Code Online (Sandbox Code Playgroud)

  • 是否有更短的版本?只需定义 ex `__le__()` 和 `__ge__()` 来使用 max 或 min 就足够了吗? (3认同)