如何在自己的类上重写或在python中执行min/max?

如何在自己的类上重写或在python中执行min/max?,python,max,min,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__

不确定这个问题的最佳标题,但我如何在我创建的类的对象上重写或执行
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
我试着重写
\uuuCMP\uuuuuu
,但似乎不起作用


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

只需覆盖比较魔法方法即可

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)
A类(对象):
定义初始值(自身,值):
自我价值=价值
定义(自身、其他):
返回self.value=其他.value
定义(自我):
返回str(self.value)
a=a(10)
b=A(20)
最小值(a,b)

您已经可以使用任意数量的参数调用
max(a,b,c,…)
,它将通过相互比较返回最大的参数。据我所知,它使用
\uuugt\uuu
\ult\uuuu
来实现这一点。不幸的是,您不能重写
max()
本身,因为它是一个内置的方法,并且不绑定到特定的类(尽管您可以很容易地编写自己的方法来完成相同的任务)。您是否希望
max()<代码> max(a,b)是b< /代码>(2)考虑<代码>函数工具。TooToRoad < /COD>(3)<代码> max(a,b,c,d)也是有效的。你现在写的东西有什么特别的错误吗?别忘了当另一个对象不是预期类的实例时,返回NotImplemented(未实现)。是否有一个较短的版本?只定义ex
\uu le\uuuu()
\uu ge\uuuu()
使用max或min是否足够?
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)