为了账号安全,请及时绑定邮箱和手机立即绑定

python3.x 的问题

python3.x 中取消了cmp这个用法,那这个题在python3.x中该怎么写啊?有没有大神可以指点一下

正在回答

2 回答

python3 的 operator 可以 但返回 正相反

In [46]: 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 __operator__(self, s):

    ...:         if self.score == s.score:

    ...:             return operator(self.name, s.name)

    ...:         return -operator(self.score, s.score)

    ...: 

    ...: L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]

    ...: print sorted(L)

    ...: 

    ...: 

[(Bob: 88), (Tim: 99), (Alice: 99)]

0 回复 有任何疑惑可以回复我~

在Python3.x ,cmp函数被operator模块代替了!!

operator.lt(a, b) ,operator.le(a, b) ,operator.eq(a, b) ,operator.ne(a, b) ,operator.ge(a, b) 
operator.gt(a, b) 这几个函数替代了原先的cmp函数。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255533    人
  • 解答问题       3038    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

python3.x 的问题

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号