为要排序的类实现__lt__是否安全?

Mat*_*und 29 python sorting

假设我的ClassA实例最终会出现在数据结构中,我们知道将在其上调用sorted().这是别人的代码,它会调用sorted(),所以我不能指定一个排序函数,但我可以实现适合ClassA的任何方法.

在我看来

def __lt__(self, other):
Run Code Online (Sandbox Code Playgroud)

是足够的,我不需要实现其他五个左右的方法(qt,eq,le,ge,ne).

这够了吗?

Ray*_*ger 37

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()))
Run Code Online (Sandbox Code Playgroud)

  • *记录*仅使用`__lt __()`来记录Python的排序,但这只是为了将来而已。我不知道这个! (2认同)
  • @Tony是的,我可以.当heapq模块从切换\ _\_乐\ _\_到\ _\_ LT\_\_它打破了扭曲这让正是这个错误(依赖于实现的细节,而忽略推荐的最佳做法).因此,我们不得不在Python 2.7中添加适配器代码,所有用户都将heapq显示为10倍.换句话说,是的,这是一种带有现实世界后果的不良做法.建议的最佳做法是有原因的.并且``functools.total_ordering``装饰器使得只需一行代码就可以轻松地遵循最佳实践. (2认同)