之前已经发过单独的缓存,这也算一种模式。

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延迟计算缓存模式的更多相关文章

  1. 大话设计模式Python实现- 享元模式

    享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度的对象. 下面是一个享元模式的demo: #!/usr/bin/env python # -*- coding:utf- ...

  2. 大话设计模式Python实现-中介者模式

    中介者模式(Mediator Pattern):用一个对象来封装一系列的对象交互,中介者使各对象不需要显示地相互引用,从而使耦合松散,而且可以独立地改变它们之间的交互. 下面是一个中介者模式的demo ...

  3. 大话设计模式Python实现-职责链模式

    职责链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而避免发送者和接收者的耦合关系.将对象连成链并沿着这条链传递请求直到被处理 下面是一个设计模式的demo: ...

  4. 大话设计模式Python实现- 抽象工厂模式

    抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类 下面是一个抽象工厂的demo: #!/usr/bin/env pyth ...

  5. 大话设计模式Python实现-工厂方法模式

    工厂方法模式(Factory Method Pattern):定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延时到其子类. #!/usr/bin/env python ...

  6. 大话设计模式Python实现-简单工厂模式

    简单工厂模式(Simple Factory Pattern):是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类. 下面使用简单工厂模式实现一个简单的四则运算 #!/usr/ ...

  7. Python类属性的延迟计算

    所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算. 优点 构造一个延迟计算属性的主要目的是为了提升性能 实现 ...

  8. 设计模式(Python)-策略模式

    本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...

  9. 设计模式(Python)-简单工厂,工厂方法和抽象工厂模式

    本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...

随机推荐

  1. log4j.properties_配置

    参考:http://blog.csdn.net/qq_30175203/article/details/52084127 参考:http://zengxiantao.iteye.com/blog/18 ...

  2. JavaScript_几种继承方式(2017-07-04)

    原型链继承 核心: 将父类的实例作为子类的原型 //父类 function SuperType() {   this.property = true; } SuperType.prototype.ge ...

  3. VirtualBox 扩展包卸载或安装失败(VERR_ALREADY_EXISTS)(转)

    文章出处:http://blog.csdn.net/leshami/article/details/9232229 最近在卸载VirtualBox出现了无法卸载的错误.提示为Failed to ins ...

  4. [Visual studio] Visual studio 2017添加引用时报错未能正确加载ReferenceManagerPackage包的解决方法

    转载原文:http://www.ynpxrz.com/n1806804c2023.aspx 1.打开VS2017下的Developer Command Prompt for VS 2017 2.然后在 ...

  5. 在AngularJS中使用谷歌地图把当前位置显示出来

    如何使用谷歌地图把当前位置显示出来呢? --在html5中,为我们提供了navigator.geolocation.getCurrentPosition(f1, f2)函数,f1是定位成功调用的函数, ...

  6. Windows 下的 Makefile 编写

    Windows 下的 Makefile 编写(一)Makefile的基本规则 作者:cntrump Makefile对于很多人来说是陌生的,特别是习惯于使用 IDE 的人来说,似乎没有听说过 Make ...

  7. windows多线程同步--互斥量

    关于互斥量的基本概念:百度百科互斥量 推荐参考博客:秒杀多线程第七篇 经典线程同步 互斥量Mutex 注意:互斥量也是一个内核对象,它用来确保一个线程独占一个资源的访问.互斥量与关键段的行为非常相似, ...

  8. jdbctemplate 获取数据表结构的方法&注意事项

    方法一 直接查询: SqlRowSet srcSqlRowSet = srcJdbcTemplate.queryForRowSet("SELECT * FROM tablename LIMI ...

  9. 【转】一次SpringMVC+ Mybatis 配置多数据源经历

    需求 现在在维护的是学校的一款信息服务APP的后台,最近要开发一些新功能,其中一个就是加入学校电影院的在线购票.在线购票实际上已经有一套系统了,但是是外包给别人开发的,我们拿不到代码只能拿到数据库,并 ...

  10. ASP.NET Web API(MVC API)

    ASP.NET Web API是​​一个框架,可以很容易构建达成了广泛的HTTP服务客户端,包括浏览器和移动设备.是构建RESTful应用程序的理想平台的.NET框架. 上面是微软对Web API给出 ...