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

如果list不仅仅包含 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 not isinstance(s,Student):

         return cmp(self.name,str(s))

         

        if self.score>s.score:

            return-1

        if self.score<s.score:

            return 1

        

        else:

            return cmp(self.name, s.name)

        


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

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

print sorted(L)


正在回答

1 回答

测试无错。如果你用python3要把最后一行改成

print(sorted(L))

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

举报

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

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

进入课程

如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错 ,如何解决

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信