Python __str__ & __repr__ & __cmp__

Source: Internet
Author: User

for (__str__), we going-see a example ...

And find who are working for ...

# !/usr/bin/python class Person (object):         def __init__ (self,name,gender):         = name        = genderif__name__'__main__'  :        = person ('Frank', page)    print p

See,the instance of (person) has a default method, just like (describe method) ...

It ' s called by Instance Self (Here,is p itself) ...

So,what It is name ...

Keep Read,you would find what's it is ...

#!/usr/bin/pythonclassPerson (object):def __init__(self,name,gender): Self.name=name Self.gender=Genderdef __str__(self):"""override the Object method"""        return 'Person object:%s,%d'%(Self.name,self.gender)if __name__=='__main__': P= Person ('Frank', 23)    PrintP

See,we got a totally different result ...

So,we know who is the method (__str__) ...

Okay,next we'll talk (__cmp__) inside method ...

#!/usr/bin/pythonclassStudent (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.score >S.score:return-1elifSelf.score <S.score:return1Else:            ifSelf.name <S.score:return-1elifSelf.name <S.name:return1Else:                return0if __name__=='__main__': L= [Student ('Tim', Student), ('Bob', Student), ('Alice', 99)]    PrintSorted (L)

Python __str__ & __repr__ & __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.