對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)
請思考如何解決。