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

python中 __cmp__

对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,可是,若是对一组 Student 类的实例排序时,就必须提供咱们本身的特殊方法 __cmp__()python

 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进行排序:spa

>>> 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进行大小排血的特殊方法:code

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

思考解决:blog

 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)
相关文章
相关标签/搜索