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

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)

原文地址:https://www.cnblogs.com/ucasljq/p/11625418.html

时间: 2024-08-05 07:13:59

python进阶五(定制类)【5-2 python中__cmp__】的相关文章

Python学习之定制类

本文和大家分享的主要是 python开发中定制类的相关内容,一起来看看吧,希望对大家学习和使用这部分内容有所帮助. 1. python中什么是特殊方法 任何数据类型的实例都有一个特殊方法:  __str__() ·  用于 print 的  __str__ ·  用于 len 的  __len__ ·  用于 cmp 的  __cmp__ ·  特殊方法定义在 class 中 ·  不需要直接调用 · Python 的某些函数或操作符会调用对应的特殊方法 file:///C:\Users\wlc

二十五 定制类

看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让class作用于len()函数. 除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类. __str__ 我们先定义一个Student类,打印一个实例: >>> class Student(object): ... def __init__(self, name):

孤荷凌寒自学python第五十二天初次尝试使用python读取Firebase数据库中记录

(完整学习过程屏幕记录视频地址在文末) 今天继续研究Firebase数据库,利用google免费提供的这个数据库服务,今天主要尝试使用firebase_admin模块来连接firebase数据库. 获得成功. 一.简单总结下今天对firebase_admin模块对象的学习 (一)要通过firebase_admin模块连接到firebase数据库,那么必须要拥有一个从firebase网站上自己的数据库的[用户和权限]处设置的'连接私钥'等相关信息的一个json文件,并下载到项目文件夹中来. (二)

Python进阶【第一篇】:Python简介

Python简介 1.Python的由来 Python是著名的"龟叔"Guido van Rossum在1989年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言. 2.C 和 Python.Java.C#等语言的联系与区别 机器码是指计算机能识别的语言--0/1,编程语言==>字节码==>机器码 其他语言: 代码编译得到 字节码 ,虚拟机执行字节码并转换成机器码再后在处理器上执行 Python 和 C Python这门语言是由C开发而来. C语言是可以用来编写操作系统

python进阶五(定制类)【5-3python中__len__】

python中 __len__ 如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数. 要让 len() 函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数. 例如,我们写一个 Students 类,把名字传进去: 1 class Students(object): 2 def __init__(self, *args): 3 self.names = args 4 def __len__(self): 5 return len(self.names

python进阶五(定制类)【5-1 python中__str__和__repr__】

python中 __str__和__repr__ 如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): 1 class Person(object): 2 def __init__(self, name, gender): 3 self.name = name 4 self.gender = gender 5 def __str__(self): 6 return '(Person: %s, %s)' % (self.name, self.gender) 现在,在交互式命令行

Python进阶-----自定制property

一.回顾python内置的装饰器@property @property的作用就是将类的函数属性同对象的数据属性一样可供对象直接调用(静态属性),而不需要加() 1 class Room: 2 def __init__(self,name,width,length): 3 self.name = name 4 self.width = width 5 self.length = length 6 7 @property #这个装饰器可以使得Room实例化的对象直接调用area这个函数属性 8 de

python进阶四(类的继承)【4-1 python中继承一个类】

python中继承一个类 如果已经定义了Person类,需要定义新的Student和Teacher类时,可以直接从Person类继承: 1 class Person(object): 2 def __init__(self, name, gender): 3 self.name = name 4 self.gender = gender 定义Student类时,只需要把额外的属性加上,例如score: 1 class Student(Person): 2 def __init__(self, n

python进阶四(类的继承)【4-4 python中多重继承】

python中多重继承 除了从一个父类继承外,Python允许从多个父类继承,称为多重继承. 多重继承的继承链就不是一棵树了,它像这样: 1 class A(object): 2 def __init__(self, a): 3 print 'init A...' 4 self.a = a 5 6 class B(A): 7 def __init__(self, a): 8 super(B, self).__init__(a) 9 print 'init B...' 10 11 class C(