python __getattr__ 巧妙应用
class ObjectDict(dict):
def __init__(self, *args, **kwargs):
super(ObjectDict, self).__init__(*args, **kwargs) def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = ObjectDict(value)
return value if __name__ == '__main__':
od = ObjectDict(asf={'a': 1}, d=True)
print od.asf, od.asf.a # {'a': 1} 1
print od.d # True
class WidgetShowLazyLoad(object):
def fetch_complex_attr(self, attrname):
'''可能是比较耗时的操作, 比如从文件读取'''
return attrname def __getattr__(self, name):
if name not in self.__dict__:
self.__dict__[name] = self.fetch_complex_attr(name)
return self.__dict__[name] if __name__ == '__main__':
w = WidgetShowLazyLoad()
print 'before', w.__dict__
w.lazy_loaded_attr
print 'after', w.__dict__
import functools
class lazy_attribute(object):
""" A property that caches itself to the class object. """ def __init__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter = func def __get__(self, obj, cls):
value = self.getter(cls)
setattr(cls, self.__name__, value)
return value class Widget(object):
@lazy_attribute
def complex_attr_may_not_need(clz):
print 'complex_attr_may_not_need is needed now'
return sum(i*i for i in range(1000)) if __name__ == '__main__':
print Widget.__dict__.get('complex_attr_may_not_need') # <__main__.lazy_attribute object at 0x02B12450>
Widget.complex_attr_may_not_need # complex_attr_may_not_need is needed now
print Widget.__dict__.get('complex_attr_may_not_need') #
class adaptee(object):
def foo(self):
print 'foo in adaptee'
def bar(self):
print 'bar in adaptee' class adapter(object):
def __init__(self):
self.adaptee = adaptee() def foo(self):
print 'foo in adapter'
self.adaptee.foo() def __getattr__(self, name):
return getattr(self.adaptee, name) if __name__ == '__main__':
a = adapter()
a.foo()
a.bar()
class AlgoImpA(object):
def __init__(self):
self.obj_attr = 'obj_attr in AlgoImpA' def foo(self):
print 'foo in AlgoImpA' def bar(self):
print 'bar in AlgoImpA' class AlgoImpB(object):
def __init__(self):
self.obj_attr = 'obj_attr in AlgoImpB' def foo(self):
print 'foo in AlgoImpB' def bar(self):
print 'bar in AlgoImpB' class Algo(object):
def __init__(self):
self.imp_a = AlgoImpA()
self.imp_b = AlgoImpB()
self.cur_imp = self.imp_a def switch_imp(self):
if self.cur_imp == self.imp_a:
self.cur_imp = self.imp_b
else:
self.cur_imp = self.imp_a def __str__(self):
return 'Algo with imp %s' % str(self.cur_imp) def __getattr__(self, name):
return getattr(self.cur_imp, name) if __name__ == '__main__':
algo = Algo() print algo
print algo.obj_attr
algo.foo() algo.switch_imp() print algo
print algo.obj_attr
algo.bar()
Algo with imp <__main__.AlgoImpA object at 0x02AA2270>
obj_attr in AlgoImpA
foo in AlgoImpA
Algo with imp <__main__.AlgoImpB object at 0x02AA22B0>
obj_attr in AlgoImpB
bar in AlgoImpB
python __getattr__ 巧妙应用的更多相关文章
- python __getattr__ & __getattribute__ 学习
实例属性的获取和拦截, 仅对实例属性(instance, variable)有效, 非类属性 getattr: 适用于未定义的属性, 即该属性在实例中以及对应的类的基类以及祖先类中都不存在 1. 动态 ...
- Python - __getattr__和__getattribute__的区别
传送门 https://docs.python.org/3/reference/datamodel.html#object.__getattr__ https://docs.python.org/3/ ...
- 某校高中生利用Python,巧妙获取考试成绩,看到成绩后无言以对!
Python是非常有吸引力的编程语言,学习Python的不是帅哥就是美女.为什么这么说呢?因为我和我的女朋友都是学习Python认识的,小编肯定是帅哥,不用去怀疑,而且我眼光特高. 给大伙讲一个故事, ...
- python __getattr__
1.__getattr__ 方法的作用:当调用不存在的属性,就会调用__getattr__()方法: 当一般位置找不到attribute的时候,会调用getattr,返回一个值或AttributeEr ...
- python __getattr__ __setattr__
class Rectangle: def __init__(self): self.width = 0 self.height = 0 def __setattr__(self, key, value ...
- python __getattr__和 __getattribute__
__getattr__ 这个魔法函数会在类中查找不到属性时调用 class User: def __init__(self): self.info = 1 def __getattr__(self, ...
- Python中__get__, __getattr__, __getattribute__的区别及延迟初始化
本节知识点 1.__get__, __getattr__, __getattribute__的区别 2.__getattr__巧妙应用 3.延迟初始化(lazy property) 1.__get__ ...
- Python数据结构与算法设计总结篇
1.Python数据结构篇 数据结构篇主要是阅读[Problem Solving with Python]( http://interactivepython.org/courselib/static ...
- [leetcode]Permutations @ Python
原题地址:https://oj.leetcode.com/problems/permutations/ 题意: Given a collection of numbers, return all po ...
随机推荐
- 数据库之Oracle——初级
世上岂无千里马,人中难得九方皋: 酒船鱼网归来是,花落故溪深一篙. 关于数据库的第一篇博客,这是我的第二次,人生第二春,什么也不想说,静静的开始吧,至于为什么写唐诗,请看第一篇文章! Oracle 初 ...
- matlab R2016a 中添加新的工具箱的方法
matlab添加新的工具箱分三步: 1. 下载新的工具箱,并解压. 2. 将解压后的工具箱文件夹移到安装的matlab中的toolbox文件夹中 3. 添加新文件夹及其子文件夹到路径中. 接下来以添加 ...
- keras 修仙笔记一
对于牛逼的程序员,人家都喜欢叫他大神:因为大神很牛逼,人家需要一个小时完成的技术问题,他就20分钟就搞定.Keras框架是一个高度集成的框架,学好它,就犹如掌握一个法宝,可以呼风唤雨.所以学keras ...
- 基于MVC设计模式的Web应用框架:struts2的简单搭建(一)
Struts2的初步介绍 Struts2是apache项目下的一个web 框架,普遍应用于阿里巴巴.京东等互联网.政府.企业门户网站.虽然之前存在了很大的安全漏洞,在2013年让苹果.中国移动.中国联 ...
- 转:聚类、K-Means、例子、细节
今天说聚类,但是必须要先理解聚类和分类的区别,很多业务人员在日常分析时候不是很严谨,混为一谈,其实二者有本质的区别. 分类其实是从特定的数据中挖掘模式,作出判断的过程.比如Gmail邮箱里有垃圾邮件分 ...
- java第一阶段测试
一.选择题(35题 * 2分)1. 下列代码编译和运行的结果是:C public static void main(String[] args) { String[] elements = { & ...
- pytesseract使用
1.安装pip install pytesseract 2.安装tesseract-ocr,下载地址:https://github.com/UB-Mannheim/tesseract/wiki,我安装 ...
- SaltStack 部署案例 02
远程执行 salt '*' state.sls apache '*':代表所有主机 state.sls :是一个模块 apache : 状态 ,表示需要部署的内容,后缀.sls YAML:三板斧 1. ...
- webuploader 实现图片批量上传
1.导入资源 2.JSP代码 <div class="page-container"> <div class="row cl"> < ...
- 使用map做数组与链表去重
#include<iostream> #include<map> using namespace std; class node{ public: node():value() ...