我正在用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”方法?
Python有一个类似的函数:^{} 。
我现在知道你在问Python3。Their "whats new" suggests:
所以看起来你可以做些
或者
在实现
__gt__()
和__lt__()
之后。然后您可以使用:
这将为您提供同等的功能。
您可以实现特殊方法
__lt__
、__gt__
等来实现自定义类型的默认运算符。有关它们的详细信息,请参见language reference。例如:
或者正如straac在评论中所说,您可以使用^{} 装饰器保存一些类型:
相关问题 更多 >
编程相关推荐