我正在做一個Python(3.2)項目,我需要比較用戶定義的對象。我已經習慣了在Java中,OOP的其中一個將定義指定該類的自然排序的一類方法compareTo()
,如下面的例子:Python的等價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__'](HTTP ://docs.python.org/reference/datamodel.html#object.__cmp__)? –