For ( __str__ ),we going to see a example ...
and find who is working for ...
#!/usr/bin/python class Person(object): def __init__(self,name,gender): self.name = name self.gender = gender if __name__ == '__main__': p = Person('Frank',23) print p
See,The instance of ( Person ) have 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 will find what's it is ...
#!/usr/bin/python class Person(object): def __init__(self,name,gender): self.name = name self.gender = gender def __str__(self): """override the object method""" return 'Person object: %s,%d' % (self.name,self.gender) if __name__ == '__main__': p = Person('Frank',23) print p
See,we got a totally different result ...
So,we know who is the method ( __str__ ) ...
Okay,next we will talk (__cmp__) inside method ...
#!/usr/bin/python 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.score > s.score: return -1 elif self.score < s.score: return 1 else: if self.name < s.score: return -1 elif self.name < s.name: return 1 else: return 0 if __name__ == '__main__': L = [Student('Tim',99),Student('Bob',88),Student('Alice',99)] print sorted(L)