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 ...
随机推荐
- Android基础Activity篇之什么是Activity?
Activity是Android的四大组件之一,也是平时我们用到最多的一个组件,可以用来显示View.官方的说法是Activity一个应用程序的组件,它提供一个屏幕来与用户交互,以便做一些诸如打电话. ...
- 照虎画猫写自己的Spring
从细节跳出来 看了部分Spring的代码,前面用了四篇内容写了一些读书笔记. 回想起来,论复杂度,Spring够喝上好几壶的.他就像一颗枝繁叶茂的大树,远处看,只是一片绿:走近看,他为你撑起一片小天地 ...
- 打字机效果-so easy
html <p> <span>有了梦想,我们的心有了飞翔:有了飞翔,我们的梦想不再遥远......</span> </p> js $(function( ...
- 并行设计模式(一)-- Future模式
Java多线程编程中,常用的多线程设计模式包括:Future模式.Master-Worker模式.Guarded Suspeionsion模式.不变模式和生产者-消费者模式等.这篇文章主要讲述Futu ...
- 实现基于Haproxy+Keepalived负载均衡高可用架构
1.项目介绍: 上上期我们实现了keepalived主从高可用集群网站架构,随着公司业务的发展,公司负载均衡服务已经实现四层负载均衡,但业务的复杂程度提升,公司要求把mobile手机站点作为单独的服务 ...
- 基于 HTML5 Canvas 的简易 2D 3D 编辑器
不管在任何领域,只要能让非程序员能通过拖拽来实现 2D 和 3D 的设计图就是很牛的,今天我们不需要 3dMaxs 等设计软件,直接用 HT 就能自己写出一个 2D 3D 编辑器,实现这个功能我觉得成 ...
- (译)ABP之依赖注入
原文地址:https://aspnetboilerplate.com/Pages/Documents/Dependency-Injection 什么是依赖注入 传统方式的问题 解决方案 构造函数注入 ...
- hdu 2586 How far away ?倍增LCA
hdu 2586 How far away ?倍增LCA 题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2586 思路: 针对询问次数多的时候,采取倍增 ...
- js 数组去重复的方法
数组去重复是js中常用的方法,归纳了四种如下: 1. for + indexOf 去重复 var arr = [3,5,5,4,1,1,2,3,7,2,5]; var target = []; fo ...
- Netty之粘包分包
粘包现象 客户端在一个for循环内连续发送1000个hello给Netty服务器端, Socket socket = new Socket("127.0.0.1", 10101); ...