ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python进阶五(定制类)【5-2 python中__cmp__】

2019-10-05 19:00:38  阅读:191  来源: 互联网

标签:__ 进阶 python self score Student cmp name


python中 __cmp__

对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__():

 1 class Student(object):
 2     def __init__(self, name, score):
 3         self.name = name
 4         self.score = score
 5     def __str__(self):
 6         return '(%s: %s)' % (self.name, self.score)
 7     __repr__ = __str__
 8 #实现print
 9     def __cmp__(self, s):
10         if self.name < s.name:
11             return -1
12         elif self.name > s.name:
13             return 1
14         else:
15             return 0
16 #实现比较类中名字(name)属性的大小,s是传入的实例

上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较,如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。

Student类实现了按name进行排序:

>>> L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)]
>>> print sorted(L)
[(Alice: 77), (Bob: 88), (Tim: 99)]

注意: 如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错,这里是一个list中均为student类的按照name进行大小排血的特殊方法:

1 L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
2 print sorted(L)

思考解决:

 1 class Student(object):
 2     def __init__(self, name, score):
 3         self.name = name
 4         self.score = score
 5 
 6     def __str__(self):
 7         return '(%s: %s)' % (self.name, self.score)
 8 
 9     __repr__ = __str__
10 
11     def __cmp__(self, s):#解决list中不仅有student类,还有包含有数字,字符串等
12         if not isinstance(s,Student):#如果list中的元素不是Student类,就直接调用cmp函数比较
13             return cmp(self.name,str(s))    
14         if self.score>s.score:
15             return-1
16         if self.score<s.score:
17             return 1     
18         else:
19             return cmp(self.name, s.name)   
20 L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
21 print sorted(L)     

任务

请修改 Student 的 __cmp__ 方法,让它按照分数从高到底排序,分数相同的按名字排序。

 1 class Student(object):
 2     def __init__(self, name, score):
 3         self.name = name
 4         self.score = score
 5 
 6     def __str__(self):
 7         return '(%s: %s)' % (self.name, self.score)
 8 
 9     __repr__ = __str__
10 
11     def __cmp__(self, s):
12         if self.score == s.score:#如果分数相等,按照名字排序
13             return cmp(self.name, s.name)
14         return -cmp(self.score, s.score)
15 
16 L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
17 print sorted(L)

 

标签:__,进阶,python,self,score,Student,cmp,name
来源: https://www.cnblogs.com/ucasljq/p/11625418.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有