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__