python __str__ & __repr__ & __cmp__
2015-06-28 15:08
501 查看
For ( __str__ ),we going to see a example ...
and find who is working for ...
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 ...
See,we got a totally different result ...
So,we know who is the method ( __str__ ) ...
Okay,next we will talk (__cmp__) inside method ...
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)
相关文章推荐
- MYSQL(python)安装记录
- python实现将html表格转换成CSV文件的方法
- 在Ubuntu 14.04 64bit上安装numpy和matplotlib库
- 使SourceInsight支持Python语言的方法
- python global vs nonlocal (2)
- python3 nonlocal vs global
- python购物淫秽数据分析(2)
- python实现根据主机名字获得所有ip地址的方法
- python自动zip压缩目录的方法
- python查找指定具有相同内容文件的方法
- Python 股票历史数据的获取
- 使用python一步一步搭建微信公众平台
- python中getaddrinfo()基本用法实例分析
- python实现搜索指定目录下文件及文件内搜索指定关键词的方法
- 分析用Python脚本关闭文件操作的机制
- [Python] 利用Django进行Web开发系列(一)
- Python遍历文件夹和读写文件的方法
- 【转】Python 代码调试技巧
- ubuntu安装python一些安装包
- python向网页提交数据