Python相当于Java的compareTo() [英] Python equivalent of Java's compareTo()
问题描述
我正在用Python(3.2)做一个项目,为此我需要比较用户定义的对象.我习惯于用Java进行OOP,在Java中将在类中定义一个compareTo()
方法,该方法指定该类的自然顺序,如下例所示:
I'm doing a project in Python (3.2) for which I need to compare user defined objects. I'm used to OOP in Java, where one would define a compareTo()
method in the class that specifies the natural ordering of that class, as in the example below:
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"方法是什么?
I'm fairly new to classes/objects in Python, so I'd like to know what is the "pythonic" way to define the natural ordering of a class?
推荐答案
您可以实现特殊方法__lt__
,__gt__
等,以实现自定义类型的默认运算符.在语言参考中查看更多有关它们的信息.
You can implement the special methods __lt__
, __gt__
etc. to implement the default operators for custom types. See more about them in the 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在评论中所述,您可以使用 total_ordering
装饰器以保存一些输入内容:
Or as said by stranac in the comments, you can use the total_ordering
decorator to save some typing:
@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
这篇关于Python相当于Java的compareTo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!