设计模式,python延迟计算缓存模式
之前已经发过单独的缓存,这也算一种模式。
from __future__ import print_function
import functools class lazy_property(object): def __init__(self, function):
self.function = function
functools.update_wrapper(self, function) def __get__(self, obj, type_):
if obj is None:
return self
val = self.function(obj)
obj.__dict__[self.function.__name__] = val
return val def lazy_property2(fn):
attr = '_lazy__' + fn.__name__ @property
def _lazy_property(self):
if not hasattr(self, attr):
setattr(self, attr, fn(self))
return getattr(self, attr)
return _lazy_property class Person(object): def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
self.call_count2 = 0 @lazy_property
def relatives(self):
# Get all relatives, let's assume that it costs much time.
relatives = "Many relatives."
return relatives @lazy_property2
def parents(self):
self.call_count2 += 1
return "Father and mother" def main():
Jhon = Person('Jhon', 'Coder')
print(u"Name: {0} Occupation: {1}".format(Jhon.name, Jhon.occupation))
print(u"Before we access `relatives`:")
print(Jhon.__dict__)
print(u"Jhon's relatives: {0}".format(Jhon.relatives))
print(u"After we've accessed `relatives`:")
print(Jhon.__dict__)
print(Jhon.parents)
print(Jhon.__dict__)
print(Jhon.parents)
print(Jhon.call_count2) if __name__ == '__main__':
main() ### OUTPUT ###
# Name: Jhon Occupation: Coder
# Before we access `relatives`:
# {'call_count2': 0, 'name': 'Jhon', 'occupation': 'Coder'}
# Jhon's relatives: Many relatives.
# After we've accessed `relatives`:
# {'relatives': 'Many relatives.', 'call_count2': 0, 'name': 'Jhon', 'occupation': 'Coder'}
# Father and mother
# {'_lazy__parents': 'Father and mother', 'relatives': 'Many relatives.', 'call_count2': 1, 'name': 'Jhon', 'occupation': 'Coder'}
# Father and mother
#
设计模式,python延迟计算缓存模式的更多相关文章
- 大话设计模式Python实现- 享元模式
享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度的对象. 下面是一个享元模式的demo: #!/usr/bin/env python # -*- coding:utf- ...
- 大话设计模式Python实现-中介者模式
中介者模式(Mediator Pattern):用一个对象来封装一系列的对象交互,中介者使各对象不需要显示地相互引用,从而使耦合松散,而且可以独立地改变它们之间的交互. 下面是一个中介者模式的demo ...
- 大话设计模式Python实现-职责链模式
职责链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而避免发送者和接收者的耦合关系.将对象连成链并沿着这条链传递请求直到被处理 下面是一个设计模式的demo: ...
- 大话设计模式Python实现- 抽象工厂模式
抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类 下面是一个抽象工厂的demo: #!/usr/bin/env pyth ...
- 大话设计模式Python实现-工厂方法模式
工厂方法模式(Factory Method Pattern):定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延时到其子类. #!/usr/bin/env python ...
- 大话设计模式Python实现-简单工厂模式
简单工厂模式(Simple Factory Pattern):是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类. 下面使用简单工厂模式实现一个简单的四则运算 #!/usr/ ...
- Python类属性的延迟计算
所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算. 优点 构造一个延迟计算属性的主要目的是为了提升性能 实现 ...
- 设计模式(Python)-策略模式
本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...
- 设计模式(Python)-简单工厂,工厂方法和抽象工厂模式
本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...
随机推荐
- git的安装以及入门
安装:https://blog.csdn.net/itpinpai/article/details/48105445 (1)下载文件 初始化 git init 连远程服务器 git remote ad ...
- 喵哈哈村的魔法考试 Round #10 (Div.2) 题解
喵哈哈村与哗啦啦村的大战(一) 最大值就是全部+3,最小值就是全部-3,注意不能降为负数. #include<bits/stdc++.h> using namespace std; con ...
- 广州移动宽带DNS
目前还搞不明白这些DNS服务器是怎么得出来的,现在只停留在网上收集. 下面是收集比较靠谱的DNS广州移动宽带的: ns3.gd.cnmobile.net 221.179.38.7 ns4.gd.cnm ...
- getOutputStream() has already been called for this response解释以及解决方法
异常:getOutputStream() has already been called for this response 的解决方法 今天在第一次接触使用“验证码”功能时,在执行时出现了异常信息: ...
- 各种组件的js 获取值 / js动态赋值
jQuery获取Select选择的Text和Value:语法解释:1. $("#select_id").change(function(){//code...}); //为Se ...
- How determine the RC time constant in PWM DAC low-pass filter?
how determine the RC time constant in PWM digital to analog low-pass filter? I 'm looking for the be ...
- iphone程序适配ipad可以用下面的宏进行尺寸改写
//判断是否为iPad #define ISIPAD [[[UIDevice currentDevice].model substringToIndex:4] isEqualToString:@&qu ...
- Linux C Socket TCP编程介绍及实例
转自:https://blog.csdn.net/lell3538/article/details/53335231 { printf("向服务器发送数据:%s\n",sendbu ...
- Comparison method violates its general contract 解决
java.lang.IllegalArgumentException: Comparison method violates its general contract! 原因 JDK7中的Collec ...
- 【OpenCV】OpenCV中GPU模块使用 (转)
CUDA基本使用方法 在介绍OpenCV中GPU模块使用之前,先回顾下CUDA的一般使用方法,其基本步骤如下: 1.主机代码执行:2.传输数据到GPU:3.确定grid,block大小: 4.调用内核 ...