与Java的compareTo()等价的Python

2024-03-28 11:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python(3.2)做一个项目,我需要比较用户定义的对象。我习惯在Java中进行面向对象编程,在类中定义一个compareTo()方法,该方法指定类的自然顺序,如下例所示:

public class Foo {
    int a, b;

    public Foo(int aa, int bb) {
        a = aa;
        b = bb;
    }

    public int compareTo(Foo that) {
        // return a negative number if this < that
        // return 0 if this == that
        // return a positive number if this > that

        if (this.a == that.a) return this.b - that.b;
        else return this.a - that.a;
    }
}

我对Python中的类/对象比较陌生,所以我想知道什么是定义类的自然顺序的“pythonic”方法?


Tags: 对象方法numberreturnifthat定义foo
2条回答

Python有一个类似的函数:^{}

我现在知道你在问Python3。Their "whats new" suggests

The cmp() function should be treated as gone, and the __cmp__() special method 
is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and 
other rich comparisons as needed. (If you really need the cmp() functionality, 
you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

所以看起来你可以做些

def compareTo(self, that):
    return ((self > that) - (self < that))

或者

@classmethod
def compare(cls, a, b):
    return ((a > b) - (a < b))

在实现__gt__()__lt__()之后。

然后您可以使用:

f1 = Foo(1,1)
f2 = Foo(2,2)

f1.compareTo(f2)
Foo.compare(f1,f2)

这将为您提供同等的功能。

您可以实现特殊方法__lt____gt__等来实现自定义类型的默认运算符。有关它们的详细信息,请参见language reference

例如:

class Foo:
    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

    def __gt__ (self, other):
        return other.__lt__(self)

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

    def __ne__ (self, other):
        return not self.__eq__(other)

或者正如straac在评论中所说,您可以使用^{}装饰器保存一些类型:

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

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

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

相关问题 更多 >