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. 2021广东省强网杯WriteUp

    个人赛 网络诈骗 参考 https://github.com/Heyxk/notes/issues/1 先把EnMicroMsg.db提出来 CompatibleInfo.cfg是0kb,用第一种方法 ...

  2. 为什么不直接去Arraylist list = new Arraylist();而是直接通过List list = new ArrayList();使用接口的好处

    ArrayList不是继承List接口,是实现了List接口. 你写成ArrayList arrayList = new ArrayList();这样不会有任何问题.和List list = new ...

  3. Python 函数 参数传递

    参数传递    在 python 中,类型属于对象,变量是没有类型的:        a=[1,2,3]        a="Runoob"    以上代码中,[1,2,3] 是 ...

  4. 菜鸡的Java笔记第三 - java 自动转换原则

    自动转换原则 数据范围保存大的数据类型要转换为数据范围保存小的数据类型,使用强制转换(强制转型就是在变量的前面加括号,在括号里写上需要强制要转的类型.) 数据范围保存小的数据类型可以自动转换为数据范围 ...

  5. 微信小程序中使用canvas

    微信小程序中使用canvas会存在的一些问题: 由于小程序在绘制canvas的时候不能加载网络图片 所以需要把网络图片保存到本地之后再进行绘制 downLoadImg: function (netUr ...

  6. [hdu6995]Travel on Tree

    问题即查询将其按照dfs序排序后,相邻两点(包括首尾)的距离和 考虑使用莫队+set维护,时间复杂度为$o(n\sqrt{n}\log n)$,无法通过 进一步的,注意到删除是可以用链表实现的,因此考 ...

  7. [atARC076E]Connected

    首先,如果没有这个平面的限制,考虑不断插入一对点,将与这两点连线有交的线从左到右,依次"移动"到左端点边上,因此一定是可行的 但当存在界限后,对于两个端点都在边界上的点对(一个端点 ...

  8. [atARC098F]Donation

    贪心,一定在最后一次经过某节点时付出$b_{u}$,条件是付出后$W\ge \max(a_{i}-b_{i},0)$(同时也可以仅考虑这个限制,因为$W$在过程中不会增大) 假设"最后一次经 ...

  9. [cf997E]Good Subsegments

    一个区间为好区间当且仅当$\max_{l\le i\le r}a_{i}-\min_{l\le i\le r}a_{i}=r-l$,考虑固定右端点$r$,维护所有左端点$l$的上述式子左-右的值,那么 ...

  10. 【JavaSE】字符编码和存储编码

    字符编码和存储编码 2019-07-15  22:34:51  by冲冲 1. 英文字母和中文汉字在不同字符集编码下的字节数不同. 英文字母 字节数 : 1; 编码:GB2312 字节数 : 1; 编 ...