如果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)