Python special function __cmp__

Source: Internet
Author: User

__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__

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.