如何使我的班级在Python中可比

我有一个Pair类(它具有一个键和一个值),我试图制作一个程序,该程序创建一堆Pair对象,将它们添加到列表中,并执行稳定的快速排序 >在他们身上。但是,我似乎无法弄清楚如何使对象具有可比性,以便程序在两个对象的键值相同时自动比较它们的键。用Java做到这一点是如此容易,但是我不知道该怎么用Python做同样的事情。

提前谢谢!

class Pair(Generic[K,V]):
    def __init__(self,key: K,val: V):
        self.key = key
        self.value = val
iCMS 回答:如何使我的班级在Python中可比

以下内容如何(可通过键对进行配对,但您可以轻松定义其他方式对其进行排序):

class Pair:
    def __init__(self,key,val):
        self.key = key
        self.value = val

    def __eq__(self,other: "Pair"):
        return self.key == other.key

    def __lt__(self,other: "Pair"):
        return self.key < other.key

    def __le__(self,other: "Pair"):
        return self.key <= other.key

    def __gt__(self,other: "Pair"):
        return self.key > other.key

    def __ge__(self,other: "Pair"):
        return self.key >= other.key

    def __str__(self):
        return f"{self.key}={self.value}"

    def __repr__(self):
        return f"{self.key}={self.value} ({id(self)})"


test = [
    Pair("a2","1"),Pair("a1","2"),Pair("b1","3"),Pair("br","4")
]

print(sorted(test))

输出:

$ python3 ~/tmp/test.py
[a1=2 (4352627216),a2=1 (4352622288),b1=3 (4352627344),br=4 (4352627408)]

要按值排序,然后按键(如果值相等)排序,例如:

    def __lt__(self,other: "Pair"):
        if self.value != other.value:
            return self.value < other.value

        return self.key < other.key

具有以上lt的示例输入/输出:

# Input
test = [
    Pair("a2","4")
]

# Output
[a2=1 (4466773648),b1=1 (4466778768),a1=2 (4466778640),br=4 (4466778832)]

此外,如果您打算将这些对用作字典键或成对使用,则可以实现__hash__。有关更多运算符,请参见here

,

Python为此使用了所谓的“ dunder方法”(双下划线方法)。您已经在使用init dunder方法。定义__eq__

编辑:看到出色的dbader article

本文链接:https://www.f2er.com/2093242.html

大家都在问