我觉得这个问题之前一定有人问过,但我找不到答案。
假设我想实现一个 Python 类,其对象可以使用 sorted()
进行排序。我是否必须重新实现所有方法,如 __lt__()
、__gt__()
等?最低限度是多少?换句话说,sorted()
调用哪些方法进行排序?
最佳答案
根据 documentation :
sort(*, key=None, reverse=False)
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
所以你只需要为你的类定义 def __lt__(self,other):
。
另见 Sorting HOW-TO在底部附近说:
The sort routines are guaranteed to use
__lt__()
when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an__lt__()
method:
关于python-3.x - 要重新定义哪些 Python 对象比较方法以使 sorted() 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68173281/