2012-01-10 61 views
20

假设我的ClassA的实例将以数据结构结束,并且我们知道sorted()将被调用。这是别人的代码,将调用sorted(),所以我不能指定一个排序函数,但我可以实现适用于ClassA的任何方法。仅仅为要分类的类实现__lt__是否安全?

这在我看来,

def __lt__(self, other): 

是足够,我不需要实现另一个五年左右的方法(QT,EQ,LE,GE,NE)。

这是否足够?

回答

27

PEP 8建议不要这样做。我还建议反对,因为这是一个脆弱的编程风格(不稳健对轻微修改代码):

相反,考虑使用functools.total_ordering类装饰做的工作:

@total_ordering 
class Student: 
    def __eq__(self, other): 
     return ((self.lastname.lower(), self.firstname.lower()) == 
       (other.lastname.lower(), other.firstname.lower())) 
    def __lt__(self, other): 
     return ((self.lastname.lower(), self.firstname.lower()) < 
       (other.lastname.lower(), other.firstname.lower())) 
+0

谢谢你,这是完美的! – 2012-01-10 00:03:27

+1

Python的排序*被记录为只使用'__lt __()',仅用于记录,但未来验证是好的。我不知道这个! – kindall 2012-01-10 05:51:14

+1

@ kindall你从我的分类指导中得到了什么?请提供一个链接,以便我可以编辑文档更清晰,不建议依赖\ _ \ _ lt \ _ \ _。 – 2012-01-10 06:36:22

相关问题