我正在用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”方式是什么?
__cmp__
这样吗? - Jeff Mercado