zoukankan      html  css  js  c++  java
  • 自定义类的排序(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)
    
    
    
  • 相关阅读:
    1697 ⑨要写信
    1220 数字三角形
    4979 数塔
    bzoj1618[Usaco2008 Nov]Buying Hay 购买干草
    bzoj1066[SCOI2007]蜥蜴
    bzoj1008[HNOI2008]越狱
    cf437D The Child and Zoo
    cf437C The Child and Toy
    cf437B The Child and Set
    cf437A The Child and Homework
  • 原文地址:https://www.cnblogs.com/xibanqiu/p/12877604.html
Copyright © 2011-2022 走看看