立即学习:https://edu.csdn.net/course/play/26755/340128?utm_source=blogtoedu
import operator
class MyClass:
def __init__(self):
self.val = 0
def __lt__(self, other):
return self.val < other.val
def __gt__(self, other):
return self.val > other.val
my1 = MyClass()
my1.val = 4
my2 = MyClass()
my2.val = 7
my3 = MyClass()
my3.val = 1
a = [my1, my2, my3]
print(a)
a.sort()
print(a[0].val, a[1].val, a[2].val)
a = [my1, my2, my3]
b = sorted(a, key=operator.attrgetter('val'))
print(b[0].val, b[1].val, b[2].val)
a.sort(key=operator.attrgetter('val'))
print(a[0].val, a[1].val, a[2].val)
# 降序 reverse 或者修改__lt__中为>,__gt__为<
a = [my1, my2, my3]
b = sorted(a, key=operator.attrgetter('val'), reverse=True)
print(b[0].val, b[1].val, b[2].val)
a.sort(key=operator.attrgetter('val'), reverse=True)
print(a[0].val, a[1].val, a[2].val)