鱼C论坛

 找回密码
 立即注册
查看: 2192|回复: 2

__cmp__的问题

[复制链接]
发表于 2016-4-10 10:06:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错:

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


请思考如何解决。



  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.     def __cmp__(self, s):
  9.         if self.name < s.name:
  10.             return -1
  11.         elif self.name > s.name:
  12.             return 1
  13.         else:
  14.             return 0
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-4-10 17:27:00 | 显示全部楼层
只有在python 2.x中才有 __cmp__方法,3.x中已经没有了,而且不同类型,放在一起排序,好像没必要吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2016-4-10 20:11:31 | 显示全部楼层
如果一定要排序的话,给sorted一个key函数:
  1. def cmp(s):
  2.     if isinstance(s, int):
  3.         return s
  4.     if isinstance(s, str):
  5.         return ord(s[0].lower())
  6.     if isinstance(s, Student):
  7.         return ord(s.name[0].upper())
  8.    
  9. L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
  10. print (sorted(L, key=cmp))
复制代码

评分

参与人数 1荣誉 +3 鱼币 +5 收起 理由
~风介~ + 3 + 5 热爱鱼C^_^

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-20 14:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表