__cmp__when sorting built-in data types such as int, str, Python's sorted () is sorted by the default comparison function CMP, but if you sort an instance of a group of Student classes, you must provide our own special method__cmp__():classStudent (object):def __init__(self, Name, score): Self.name=name Self.score=scoredef __str__(self):return '(%s:%s)'%(Self.name, Self.score)__repr__=__str__ def __cmp__(self, s):ifSelf.name <S.name:return-1elifSelf.name >S.name:return1Else: return0 The above Student class implements the __cmp__ () method,__cmp__ using instance self and incoming instances to compare, if self should be in front, return-1, if s should be in front, return 1 if both are equal, return 0. The student class implements sorting by name:>>> L = [Student ('Tim', Student), ('Bob', Student), ('Alice', 77)]>>>PrintSorted (L) [(Alice:(bob:88), (tim:99) Note: If the list contains more than just the Student class,__cmp__may be error: L= [Student ('Tim', Student), ('Bob', 88), 100,'Hello']PrintSorted (L) Please think about how to solve.
classStudent (object):def __init__(self, Name, score): Self.name=name Self.score=scoredef __str__(self):return '(%s:%s)'%(Self.name, Self.score)__repr__=__str__ def __cmp__(self, s):if(self.score<s.score):return1if(self.score>s.score):return-1if(self.score==s.score):if(self.name>s.name):return1; if(self.name<s.name):return-1return0L= [Student ('Tim', Student), ('Bob', Student), ('Alice', 99)]PrintSorted (L)
Python special function __cmp__