django 中的延迟加载技术,python中的lazy技术
---恢复内容开始---
说起lazy_object,首先想到的是django orm中的query_set、fn.Stream这两个类。
query_set只在需要数据库中的数据的时候才 产生db hits。Stream对象只有在用到index时才会去一次次next。
1行生成了斐波那契数列。
说明:
f是个lazy的对象,f首先放入了0和1,然后放入了迭代器iters.map。等f[2]的时候。就会调用1次next(iters.map(add, f, iters.drop(1, f))),在map的迭代器中,next(f)和next(drop(1,f))被放到add两端。
很高端大气上档次有木有!
这里有个django的lazy的实现代码,
对象的
#coding: utf-8
#
class LazyProxy(object): def __init__(self, cls, *args, **kwargs): self.__dict__['_cls'] = cls
self.__dict__['_params'] = args
self.__dict__['_kwargs'] = kwargs self.__dict__["_obj"]=None def __getattr__(self, item): if self.__dict__['_obj'] is None:
self._init_obj() return getattr(self.__dict__['_obj'], item) def __setattr__(self, key, value): if self.__dict__['_obj'] is None:
self._init_obj() setattr(self.__dict__['_obj'], key , value) def _init_obj(self): self.__dict__['_obj']=object.__new__(self.__dict__['_cls'],
*self.__dict__['_params'],
**self.__dict__['_kwargs'])
self.__dict__['_obj'].__init__(*self.__dict__['_params'],
**self.__dict__['_kwargs']) class LazyInit(object): def __new__(cls, *args, **kwargs):
return LazyProxy(cls, *args, **kwargs) class A(LazyInit): def __init__(self, x): print ("Init A")
self.x = 14 + x a = A(1)
print "Go"
print a.x
原理:在类的__new__方法中hook一下,使其返回lazy_proxy 的对象。然后调用__init__方法时,其实就是调用proxy的__init__方法,第一次调用时
也就是当A生成实例时,Proxy才会真正产生一个A的类,并初始化这个类,注意,在这里proxy的init中得到的cls是A而不是Lazy_Init,因为只有A(1)调用时A的__new__才会调用,虽然__new__名字的查找在LazyInit中。
函数的lazy:
"""
lazy - Decorators and utilities for lazy evaluation in Python
Alberto Bertogli (albertito@blitiri.com.ar)
""" class _LazyWrapper:
"""Lazy wrapper class for the decorator defined below.
It's closely related so don't use it. We don't use a new-style class, otherwise we would have to implement
stub methods for __getattribute__, __hash__ and lots of others that
are inherited from object by default. This works too and is simple.
I'll deal with them when they become mandatory.
"""
def __init__(self, f, args, kwargs):
self._override = True
self._isset = False
self._value = None
self._func = f
self._args = args
self._kwargs = kwargs
self._override = False def _checkset(self):
print '', self._isset, self._value
if not self._isset:
self._override = True
self._value = self._func(*self._args, **self._kwargs)
self._isset = True
self._checkset = lambda: True
self._override = False def __getattr__(self, name):
print '----------getattr----', name
if self.__dict__['_override']:
return self.__dict__[name]
self._checkset()
print '@@@@@@@@@', self._value, type(self._value), name, self._value.__getattribute__(name)
return self._value.__getattribute__(name) def __setattr__(self, name, val):
print '----------setattr----', name, val
if name == '_override' or self._override:
self.__dict__[name] = val
return
self._checkset()
print ''
setattr(self._value, name, val)
return def lazy(f):
"Lazy evaluation decorator"
def newf(*args, **kwargs):
return _LazyWrapper(f, args, kwargs) return newf @lazy
def quick_exe():
print '---------quick exe-----------'
return 'quickquick' import pdb
#pdb.set_trace() quick_exe()
print '#####################'
print quick_exe()
---恢复内容结束---
django 中的延迟加载技术,python中的lazy技术的更多相关文章
- Python中什么是变量Python中定义字符串
在Python中,变量的概念基本上和初中代数的方程变量是一致的. 例如,对于方程式 y=x*x ,x就是变量.当x=2时,计算结果是,当x=5时,计算结果是25. 只是在计算机程序中,变量不仅可以是数 ...
- numpy中int类型与python中的int
[code] import numpy as np nparr = np.array([[1 ,2, 3, 4]]) np_int32 = nparr[0][0] # np_int=1 py_int ...
- Python中利用函数装饰器实现备忘功能
Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下 " ...
- Python中metaclass解释
Classes as objects 首先,在认识metaclass之前,你需要认识下python中的class.python中class的奇怪特性借鉴了smalltalk语言.大多数语言中,clas ...
- 可爱的 Python : Python中函数式编程,第二部分
英文原文:Charming Python: Functional programming in Python, Part 2,翻译:开源中国 摘要: 本专栏继续让David对Python中的函数式编 ...
- [Python]Python章1 Python中_的故事
_xx 单下划线开头 Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范. 本文为译文,版 ...
- 数据库MySql在python中的使用
随着需要存储数据的结构不断复杂化,使用数据库来存储数据是一个必须面临的问题.那么应该如何在python中使用数据库?下面就在本篇博客中介绍一下在python中使用mysql. 首先,本博客已经假定阅读 ...
- Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据
背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlw ...
- Python中:self和__init__的含义 + 为何要有self和__init__
Python中:self和__init__的含义 + 为何要有self和__init__ 背景 回复: 我写的一些Python教程,需要的可以看看 中SongShouJiong的提问: Python中 ...
- Python 中的类的相关操作
构造函数 构造函数是任何类都有的特殊方法.当要创建一个类时,就要调用构造函数.他的名字是__init__.init的前后分别是两个下划线.时间类Time的构造函数如下: >>> cl ...
随机推荐
- MyDetailedOS
http://njumdl.sinaapp.com/ https://github.com/mudongliang
- cocos2dx 公告效果
第一种方法: http://blog.csdn.net/jackystudio/article/details/12991977 [玩转cocos2d-x之十六]滚动字幕和公告 第二种方法: http ...
- 深入理解计算机系统第二版习题解答CSAPP 2.14
假设x和y的字节值分别为0x66和0x39.填写下表,指明各个C表达式的字节值. 0x66 = 0110 0110(B) 0x39 = 0011 1001(B) 表达式 值 x & y 0x2 ...
- Windows2012中Jenkins搭建.NET自动编译测试与发布环境
安装7Zip 下载地址: http://www.7-zip.org/a/7z1602-x64.exe 安装Git 下载地址:https://github.com/git-for-windows/git ...
- 关于JSP异常的处理
jsp中错误处理页面-isErrorPage="true" 举例说明:mustBeError.jsp <%@ page contentType="text/html ...
- javascript/jquery给动态加载的元素添加click事件
/** 这种写法:在重新加载数据后事件依然有效*/$(document).on('click', '#district_layer ul li', function () { });
- SSM成功了
- 使用blktrace排查iowait cpu高的问题
本文转自这里,blktrace在这种情况下的使用方法值得借鉴学习. ------------------------------------------------------------------ ...
- NetMQ(ZeroMQ)Client => Server => Client 模式的实现
ØMQ (也拼写作ZeroMQ,0MQ或ZMQ)是一个为可伸缩的分布式或并发应用程序设计的高性能异步消息库.它提供一个消息队列, 但是与面向消息的中间件不同,ZeroMQ的运行不需要专门的消息代理(m ...
- ubuntu 12.04 lts安装golang并设置vim语法高亮
安装golang sudo apt-get install golang 设置vim语法高亮 sudo apt-get install vim-gocomplete gocode vim-syntax ...