代码之家  ›  专栏  ›  技术社区  ›  user1179317

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

  •  -1
  • user1179317  · 技术社区  · 6 年前

    不确定这个问题的最佳标题,但我如何重写或执行 min(a, b) max(a, b) 关于我做的类的东西?我可以超越 gt 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
    

    前任:

    a = MyClass(2,3)
    b = MyClass(3,3)
    
    print(a > b)
    # False
    

    我试图超越 __cmp__

    希望能够做到 最大值(a,b) 然后回来 b

    1 回复  |  直到 6 年前
        1
  •  2
  •   Muruganandhan Peramagounder    6 年前

    只是重写比较魔术方法

    class A(object):
    
        def __init__(self, value):
            self.value = value
    
        def __lt__(self, other):
            return self.value < other.value
    
        def __lt__(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)