小编Mar*_*ley的帖子

在 Python 中,如何使用自定义键与多个值进行比较?

在实现类的__eq____lt__方法时,通常的做法是使用元组对要比较的值进行分组,如下所示:

@total_ordering
class Foo(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __hash__(self):
        return hash((self.c, self.a, self.b))

    def __eq__(self, other):
        return (self.c, self.a, self.b) == (other.c, other.a, other.b)

    def __lt__(self, other):
        return (self.c, self.a, self.b) < (other.c, other.a, other.b)
Run Code Online (Sandbox Code Playgroud)

然而,这使用了每个键的自然顺序。如果我想改变,例如,如何a排序?

到目前为止,这是我想出的,虽然它似乎工作正常,但我想知道是否有更好的方法来解决它:

@total_ordering
class Foo(object):
    def __init__(self, a, b, c):
        self.a = MyA(a) # Note
        self.b = b
        self.c = c

    def __hash__(self):
        return hash((self.c, self.a, self.b))

    def …
Run Code Online (Sandbox Code Playgroud)

python

4
推荐指数
1
解决办法
2060
查看次数

标签 统计

python ×1