Python 自定义类的排序

发布时间:2019-09-26 10:43:25编辑:auto阅读(2298)

    Python 里面自定义类的时候, 一般需要重写几个方法, __init__ 一般是构造函数

    这里面有一个__cmp__() 是比较函数, 重写它的时候,一定要记得返回值有三个,0,±1  !! 而不是返回0,1   这里没有注意,导致在排序的时候,一直出错啊,QAQ

    或者直接使用内置函数 cmp() 来返回就行

    def __cmp__(self,other):
    		if self.age<other.age:
    			return -1
    		elif self.age==other.age:
    			return 0
    		else:
    			return 


    上述的等价于:

    这样再重写了这个__cmp__ 函数之后,就可以为类列表排序了

    def __cmp__(self,other):
    		return cmp(self.age,other.age)


    看例子:

    class Prople:
    	"""docstring for Prople"""
    	
    	def __init__(self,n,a):
    		self.name=n
    		self.age=a
    	def __cmp__(self,other):
    		return cmp(self.age,other.age)
    
    	def __str__(self):
    		return self.name+" "+str(self.age)
    
    
    p=Prople("liu",60)
    pp=Prople("li",50)
    
    li=[]
    li.append(p)
    li.append(pp)
    print sorted(li)[0]

    这次老老实实的记住了!! 排序坑了好长时间。。。。 伤不起。。。

关键字