我正在用Python(3.2)做一个项目,我需要比较用户定义的对象。我习惯了Java中的OOP,在那里,我们将定义类中的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中的类/对象还比较陌生,所以我想知道定义类的自然顺序的“蟒蛇式”方法是什么?

最佳答案

您可以实现特殊的方法来实现自定义类型的默认操作符。有关它们的更多信息,请参见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)

或者如Stranac在评论中所说,您可以使用__lt__修饰器保存一些输入:
@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

10-08 07:54