class MyClass:
def __init__(self):
self.value = 0
'''
def __gt__(self, other):
return self.value > other.value
'''
def __lt__(self, other):
return self.value > other.value
my1 = MyClass()
my1.value = 20
my2 = MyClass()
my2.value = 10
my3 = MyClass()
my3.value = 30
a = [my1, my2, my3]
print(a)
import operator
# a.sort()
a.sort(key=operator.attrgetter('value'))
b = sorted(a, key=operator.attrgetter('value'))
print(a[0].value)
print(a[1].value)
print(a[2].value)
print(b[0].value)
[<__main__.MyClass object at 0x00000205D1AB5DA0>, <__main__.MyClass object at 0x00000205D1AB5668>, <__main__.MyClass object at 0x00000205D1AB5D68>]
10
20
30
10
# a.sort(key=operator.attrgetter('value'), reverse=True)
a.sort()
print(a[0].value)
print(a[1].value)
print(a[2].value)
30
20
10
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有