Ildar Asked:2021-12-24 03:52:33 +0000 UTC2021-12-24 03:52:33 +0000 UTC 2021-12-24 03:52:33 +0000 UTC 什么比较方法足以在python中重载,以便您可以对自己类的对象进行排序 772 我有一个自定义类,它需要按特定属性排序(您可以从属性中抽象出来),我需要重载哪些比较方法才能使排序正常工作?因为在我看来,所有方法都被冗余地重载了 python 1 个回答 Voted Best Answer Danis 2021-12-24T04:09:14Z2021-12-24T04:09:14Z 您需要覆盖该__lt__方法__gt__ class my1: def __lt__(self, other): print("__lt__") return True class my2: def __gt__(self, other): print("__gt__") return True sorted([my1(), my1()]) sorted([my2(), my2()]) 如果你覆盖两者,它只会使用__lt__ class my: def __lt__(self, other): print("__lt__") return True def __gt__(self, other): print("__gt__") return True sorted([my(), my()])
您需要覆盖该
__lt__方法__gt__如果你覆盖两者,它只会使用
__lt__