python特殊函数 __cmp__
__cmp__
对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__(): class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__ def __cmp__(self, s):
if self.name < s.name:
return -1
elif self.name > s.name:
return 1
else:
return 0
上述 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__ 可能会报错: L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
print sorted(L)
请思考如何解决。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if(self.score<s.score):
return 1
if(self.score>s.score):
return -1
if(self.score==s.score):
if(self.name>s.name):
return 1;
if(self.name<s.name):
return -1
return 0
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
python特殊函数 __cmp__的更多相关文章
- python特殊函数
__doc__ 类(实例).__doc__ 类的描述信息 '''class des''' __module__ 类(实例).__module__ 表示当前操作的对象在那个模块 __class__ ...
- Python比较函数__cmp__
#!/usr/bin/python class my_type(object): def __init__(self, v): self.value = v def __cmp__(self, v2) ...
- python中 __cmp__
对 int.str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法__cmp_ ...
- python特殊函数 __call__()
__call__ 在Python中,函数其实是一个对象: >>> f = abs >>> f.__name__ 'abs' >>> f(-123) ...
- Python 特殊函数解析(lambda 函数,map 函数,filter 函数,reduce 函数)
写在之前 今天给大家介绍几个比较特殊的函数,他们具有函数式编程的特点,有人将它们视为 Python 可进行 「函数式编程」 的见证,至于什么是函数式编程,不是本篇文章的重点,感兴趣的可以去了解一下.老 ...
- 【转载】python 特殊函数 dunder function
python的特殊方法:另外一种称谓是 dunder function, 就是 under-under function的简写,就是指那些前后都带双下划线的函数. 转自这里: https://blog ...
- python特殊函数 __len__(self):
__len__ 如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数. 要让 len() 函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数. 例如,我们 ...
- python特殊函数__str__、__repr__和__len__
1.__str__ 首先介绍__str__ class Students(object): def __init__(self, *args): self.names = args # def __s ...
- Python起步
最近研究系统自动化测试想起了一年前有学习Python的想法,借此机会准备抽时间好好学学.为方便以后学习和查询特写以下博客! Python基础 1. Python数据结构 (1)Python字符串 (2 ...
随机推荐
- 用C#读取txt文件的方法
1.使用FileStream读写文件 文件头: using System;using System.Collections.Generic;using System.Text;using System ...
- Python~if,while,for~顺序,判断,循环
if A: for -in : while x: if A:elif:else: 不能直接用int进行迭代,而必须加个range. range(len(L)) int ob ...
- cmd命令查看局域网内计算机信息
ping [计算机名] ping -a [IP] nbtstat -a [IP] net view arp -a nslookup www.baidu.com 查看当前dns地址 tracert [I ...
- 3.saltstack的grains和pillar学习笔记
作者:刘耀 QQ:22102107 SaltStack_Grains Grains grains是minion第一次启动的时候采集的静态数据,可以用在salt的模块和其他组件中.其实grains在每次 ...
- C#获取IP和主机名
System.Net.IPAddress addr; //获取IP addr = new System.Net.IPAddress ( Dns.GetHostByName ( Dns.GetHostN ...
- 零件分组_DP
问题 C: 零件分组 时间限制: 1 Sec 内存限制: 64 MB提交: 31 解决: 14[提交][状态][讨论版] 题目描述 某工厂生产一批棍状零件,每个零件都有一定的长度(Li)和重量(W ...
- codeforces 338(Div 2) B. Longtail Hedgehog 解题报告
题目链接:http://codeforces.com/problemset/problem/615/B 题目意思:要画一只 hedgehog,由 tail 和 spines 组成.我们要求得 beau ...
- window.location.href url含中文服务器收到乱码问题解决
中文乱码问题 window.location.href url含中文服务器收到乱码问题解决 (1).页面中先对中文进行编码. 如:window.location.href = url+"&a ...
- iOS-Runtime-Headers
iOS8.4 及之前的头文件 私有及共有API https://github.com/nst/iOS-Runtime-Headers
- STL_advance distance prev next
template<class InputIterator> typename iterator_traits<InputIterator>::difference_type d ...