Python版

https://github.com/faif/python-patterns/blob/master/creational/lazy_evaluation.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- """
Lazily-evaluated property pattern in Python. https://en.wikipedia.org/wiki/Lazy_evaluation *References:
bottle
https://github.com/bottlepy/bottle/blob/cafc15419cbb4a6cb748e6ecdccf92893bb25ce5/bottle.py#L270
django
https://github.com/django/django/blob/ffd18732f3ee9e6f0374aff9ccf350d85187fac2/django/utils/functional.py#L19
pip
https://github.com/pypa/pip/blob/cb75cca785629e15efb46c35903827b3eae13481/pip/utils/__init__.py#L821
pyramimd
https://github.com/Pylons/pyramid/blob/7909e9503cdfc6f6e84d2c7ace1d3c03ca1d8b73/pyramid/decorator.py#L4
werkzeug
https://github.com/pallets/werkzeug/blob/5a2bf35441006d832ab1ed5a31963cbc366c99ac/werkzeug/utils.py#L35 *TL;DR80
Delays the eval of an expr until its value is needed and avoids repeated evals.
""" 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
# 1

Python转载版

【编程思想】【设计模式】【创建模式creational】lazy_evaluation的更多相关文章

  1. 【编程思想】【设计模式】【创建模式creational 】工厂模式factory_method

    Python版 https://github.com/faif/python-patterns/blob/master/creational/factory_method.py #!/usr/bin/ ...

  2. 【编程思想】【设计模式】【创建模式creational】Pool

    Python版 https://github.com/faif/python-patterns/blob/master/creational/pool.py #!/usr/bin/env python ...

  3. 【编程思想】【设计模式】【创建模式creational】Borg/Monostate

    Python版 https://github.com/faif/python-patterns/blob/master/creational/borg.py #!/usr/bin/env python ...

  4. 【编程思想】【设计模式】【创建模式creational】抽象工厂模式abstract_factory

    Python版 https://github.com/faif/python-patterns/blob/master/creational/abstract_factory.py #!/usr/bi ...

  5. 【编程思想】【设计模式】【创建模式creational】建造者模式builder

    Python版 https://github.com/faif/python-patterns/blob/master/creational/builder.py #!/usr/bin/python ...

  6. 【编程思想】【设计模式】【创建模式creational】原形模式Prototype

    Python版 https://github.com/faif/python-patterns/blob/master/creational/prototype.py #!/usr/bin/env p ...

  7. 【java设计模式】【创建模式Creational Pattern】单例模式Singleton Pattern

    //饿汉式:资源利用率较低(无论是否需要都会创建),性能较高(使用前无需判断实例是否存在,可直接使用) public class EagerSingleton{ private static fina ...

  8. 【java设计模式】【创建模式Creational Pattern】抽象工厂模式Abstract Factory Pattern

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW0AAABvCAIAAACo3AbKAAALvUlEQVR4nO1dUa7cOA7U/c+zwJxkf4

  9. 【java设计模式】【创建模式Creational Pattern】建造模式Builder Pattern

    package com.tn.pattern; public class Client { public static void main(String[] args) { Director dire ...

随机推荐

  1. mysql批量修改某一列的值为另外的值

    sql语句 UPDATE tb_info SET org_id = 2170 WHERE org_id = 815

  2. building sasl.wrapper extention

    yum install gcc-c++ python-devel.x86_64 cyrus-sasl-devel.x86_64 pip install pyhs2 ref: https://www.o ...

  3. 3组-Alpha冲刺-1/6

    一.基本情况 队名:发际线和我作队 组长博客:链接 小组人数:10 二.冲刺概况汇报 黄新成(组长) 过去两天完成了哪些任务 文字描述 组织会议,讨论了alpha冲刺的分工,确定了收集数据的渠道,为拍 ...

  4. 大爽Python入门教程 1-5 答案

    大爽Python入门公开课教案 点击查看教程总目录 1 方向变换 >>> 51//4 12 >>> 51%4 3 答: 向左转51次之后, 小明面朝东方, 转过了1 ...

  5. 在 Kubernetes 上安装 Gitlab CI Runner Gitlab CI 基本概念以及 Runner 的安装

    简介 从 Gitlab 8.0 开始,Gitlab CI 就已经集成在 Gitlab 中,我们只要在项目中添加一个.gitlab-ci.yml文件,然后添加一个Runner,即可进行持续集成.在介绍 ...

  6. 分布式条件下Integer大小比值的问题

    目录 起因 但是,搞大数据的同学请注意了! 动机 验证 处理 起因 临下班,偶然看到阿里巴巴<JAVA开发手册>中,关于整型包装类对象之间值的比较的规约,里面提到强制使用equals,而不 ...

  7. SpringCloud升级之路2020.0.x版-38. 实现自定义 WebClient 的 NamedContextFactory

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 实现 WeClient 的 NamedContextFactory 我们要实现的是不同微服 ...

  8. [loj2265]最长上升子序列

    以下内容参考2019年集训队论文<浅谈杨氏矩阵在信息学竞赛中的应用> 1.前置知识 杨表 标准杨表:一张网格图,满足以下条件-- 1.设其有$m$行.第$i$行有$a_{i}$个格子(格子 ...

  9. go程序不停机重启

    让我们给http服务写一个版本更新接口,让它自动更新版本并重启服务吧. 初步例子 注:为了精简,文中代码都去除了err处理 main.go var Version = "1.0" ...

  10. ISIJ2021 游记

    Day -419 ~ ? - 2020.5.8 ~ ? 咦?ISIJ2021 怎么会扯到 2020 年的事情呢? 好吧这似乎真的是一个长篇大论,事情真的要从那一天开始讲起-- 仍依稀记得 2020 年 ...