类的定制
2015-11-30 20:04
218 查看
今天在网上看了篇文件,关于类的定制,原来类也能那么风骚的使用啊,涨了不少知识,一时半会还没消化呢,先把自己的练习代码贴上,后面慢慢吃透。
__author__ = 'lulongfei' class Student(object): def __init__(self, name): self.name = name print Student('Michael') class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name: %s)'% self.name # print Student('Michael') s = Student('Michael') print (s) class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name :%s)'%self.name __repr__ = __str__ s = Student('Michael') s class Fib(object): def __init__(self): self.a, self.b = 0, 1 def __iter__(self): return self def next(self): self.a, self.b = self.b, self.a + self.b if self.a > 1000: raise StopIteration() return self.a for n in Fib(): print n class Fib(object): def __getitem__(self, n): if isinstance(n, int): a, b = 1, 1 for x in range(n): a, b = b, a + b return a if isinstance(n, slice): start = n.start stop = n.stop a, b = 1, 1 L = [] for x in range(stop): if x >= start: L.appent(a) a, b = b, a + b return L class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr == 'score': return 99 s = Student() print s.name print s.score class Student(object): def __getattr__(self, attr): if attr == 'age': return lambda : 25 a = Student() print a.age() class Student(object): def __getattr__(self, attr): if attr == 'age': return lambda :25 raise AttributeError('\'Student\' object has no attribute\'%s\''% attr) s = Student() s.name class Student(object): def __init__(self, name): self.name = name def __call__(self): print 'My name is %s.'%self.name s = Student('Michael') s() callable(Student()) print callable(max)
相关文章推荐
- 36.block循环引用的问题
- win10 输入法禁用IME
- 模拟n个人参加选举的过程,并输出选举结果:假设候选人有四人,分别用A,B,C,D表示,当选某候选人时,直接输入其编号(编号由计算机随机产生,若输入的不是A,B,C,D则视为无效票,选举结束后按得票数从高到底输出候选人编号和所得票数.
- bootstrap快速入门笔记(三)响应式,行,列,偏移量,排序
- 数据库概念小结
- 第八周实践项目5—计数的模式匹配
- Android: 网络请求Error,socket error可能原因之-1
- 杭电ACM1098 Ignatius's puzzle
- UI-1-UI入门
- Bootstrap 折叠(collapse)插件面板
- 导购的路上,媒体向左,社区向右
- 黑马程序员——Objective-C面向对象self和super关键词的用法笔记和举例
- 视觉感知特性【3】基于视觉关注的图像显著性分析
- 终端中管理SVN服务器 上传、下载、更新
- LINUX集群技术构建ANSYS分布式高性能计算平台
- iOS---导航条右边加多个item
- jsp的注册登陆链接数据库验证
- Android屏幕适配
- 基于AFNetworking封装的网络请求工具类
- MIT算法导论-第五讲-线性时间排序