深入学习Django源码基础4 - python的动态延时加载技术(lazy)

本文探讨了在Python中如何实现动态延时加载技术,特别是在Django框架下应用。通过代理类和延迟初始化,避免了在程序启动时不必要的计算和资源消耗。介绍了Python实现这一技术的基本思路和对象构造方法,提供了相关参考文章链接以供深入学习。

在编程时候经常会遇到这样情况

程序中需要1个示例,但是这个示例当前用不到。初始化和计算需要一定的时间。

这个时候就要用到动态延时加载技术。一般手段有代理类,线程。计时器。

在python中也有这样方法。

python中方法的思路是:

构造1个代理类,保存对象或者函数的名称,参数。

实际调用时候,在初始化对象,计算。


参考文章:点击打开链接


对象的构造方法如下

#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

函数的

""" 
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 '111111111111', 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 '222222222222222'  
        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()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值