自定义类的排序(pyhton3.7)和pyhton 2.7不能使用的原因
python 2.X的错误
class Image:
def __init__(self,path,name,boardName):
self.name = name
self.boardName = boardName
self.path = path
def __cmp__(self, other):
if self.name > other.name:
return -1
elif self.name == other.name:
return 0
else:
return 1
a=Image("a",1589250493309,"1")
b=Image("b",1589250508420,"1")
li = []
li.append(b)
li.append(a)
print(li)
print(sorted(li))
上面的代码会出现 如图的错误
原因是 :python 3.x 把__cmp__ 给去掉了。虽然你写了这个方法,实际上,这个代码没有生效,没有实现这个类的比较。
文章参考:https://www.zhihu.com/question/47895103
python3.7 的实现
from functools import total_ordering
@total_ordering
class Image:
def __init__(self,path,name,boardName):
self.name = name
self.boardName = boardName
self.path = path
def __eq__(self, other):
return self.name == other.name
def __lt__(self, other):
return self.name < other.name
a=Image("a",1589250493309,"1")
b=Image("b",1589250508420,"1")
li = []
li.append(b)
li.append(a)
print(li[0].name)
print(sorted(li)[0].name)