好代码系列(一):LazyObject
site-packages/django/utils/functional.py
def new_method_proxy(func):
def inner(self, *args):
if self_wrapped is empty:
self._setup()
return func(self._wrapped, *args)
return inner class LazyObject(object):
"""
A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the
instantiation. If you don't need to do that, use SimpleLazyObject.
""" # Avoid infinite recursion when tracing __init__ (#19456).
_wrapped = None def __init__(self):
self._wrapped = empty __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value):
if name == "_wrapped":
# Assign to __dict__ to avoid infinite __setattr__ loops.
self.__dict__["_wrapped"] = value
else:
if self._wrapped is empty:
self._setup()
setattr(self._wrapped, name, value) def __delattr__(self, name):
if name == "_wrapped":
raise TypeError("can't delete _wrapped.")
if self._wrapped is empty:
self._setup()
delattr(self._wrapped, name) def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError('subclasses of LazyObject must provide a _setup() method') # Because we have messed with __class__ below, we confuse pickle as to what
# class we are pickling. We're going to have to initialize the wrapped
# object to successfully pickle it, so we might as well just pickle the
# wrapped object since they're supposed to act the same way.
#
# Unfortunately, if we try to simply act like the wrapped object, the ruse
# will break down when pickle gets our id(). Thus we end up with pickle
# thinking, in effect, that we are a distinct object from the wrapped
# object, but with the same __dict__. This can cause problems (see #25389).
#
# So instead, we define our own __reduce__ method and custom unpickler. We
# pickle the wrapped object as the unpickler's argument, so that pickle
# will pickle it normally, and then the unpickler simply returns its
# argument.
def __reduce__(self):
if self._wrapped is empty:
self._setup()
return (unpickle_lazyobject, (self._wrapped,)) # We have to explicitly override __getstate__ so that older versions of
# pickle don't try to pickle the __dict__ (which in the case of a
# SimpleLazyObject may contain a lambda). The value will end up being
# ignored by our __reduce__ and custom unpickler.
def __getstate__(self):
return {} def __deepcopy__(self, memo):
if self._wrapped is empty:
# We have to use type(self), not self.__class__, because the
# latter is proxied.
result = type(self)()
memo[id(self)] = result
return result
return copy.deepcopy(self._wrapped, memo)
好代码系列(一):LazyObject的更多相关文章
- iOS开发一行代码系列:一行搞定输入框
近期总结了下开发过程中经常使用的功能,发现有时候我在做反复性的劳动.于是决定把经常使用的功能抽出来,方便下次使用. 我的想法是:用最少的代码来解决这个问题.于是写了一些经常使用的工具类,名字就叫一行代 ...
- 自适应大邻域搜索代码系列之(1) - 使用ALNS代码框架求解TSP问题
前言 上次出了邻域搜索的各种概念科普,尤其是LNS和ALNS的具体过程更是描述得一清二楚.不知道你萌都懂了吗?小编相信大家早就get到啦.不过有个别不愿意透露姓名的热心网友表示上次没有代码,遂不过瘾啊 ...
- 二叉树(LeetCode) C++相关知识代码 系列1
0.二叉树最大深度 原题目:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes a ...
- 编写高质量的Python代码系列(八)之部署
Python提供了一些工具,使我们可以把软件部署到不同的环境中.它也提供了一些模块,令开发者可以把程序编写的更加健壮.本章讲解如何使用Python调试.优化并测试程序,以提升其质量与性能. 第五十四条 ...
- 编写高质量的Python代码系列(七)之协作开发
如果多个人要开发同一个Python程序,那就得仔细商量代码的写法了.即使你是一个人开发,也需要理解其他人所写的模块.本节讲解多人协作开发Python程序时所用的标准工具及最佳做法. 第四十九条:为每个 ...
- 编写高质量的Python代码系列(六)之内置模块
Python预装了许多写程序时会用到的重要模块.这些标准软件包与通常意义上的Python语言联系得非常精密,我们可以将其当成语言规范的一部分.本节将会讲解基本的内置模块. 第四十二条:用functoo ...
- 编写高质量的Python代码系列(四)之元类及属性
元类(metaclass)及动态属性(dynamic attribute)都是很强大的Python特性,然后他们也可能导致及其古怪.及其突然的行为.本节讲解这些机制的常见用法,以确保各位程序员写出来的 ...
- 编写高质量的Python代码系列(二)之函数
Python中的函数具备多种特性,这可以简化编程工作.Python函数的某些性质与其他编程语言中的函数相似,但也有性质是Python独有的.本节将介绍如何用函数来表达亿图.提升可复用程度,并减少Bug ...
- 少侠学代码系列(一)->JS起源
少侠:喂,有人吗?赶紧出来接客了,有没有人啊 帅气的我:来了来了,少侠有何吩咐? 少侠:把你们店里的秘籍呈上来我要学JS 帅气的我:少侠,别这样,我们秘籍是不外传的,祖上传下来的规矩,传人妖不传男女. ...
随机推荐
- sqlServer下展示某库中所有的表
- Linux提权(1)-基础版~
利用Linux内核漏洞提权 VulnOS version 2是VulHub上的一个Linux提权练习,当打开虚拟机后,可以看到 获取到低权限SHELL后我们通常做下面几件事 1.检测操作系统的发行版本 ...
- Error:Execution failed for task ':app:transformClassesWithDexForDebug'解决记录
转载请标明出处: http://blog.csdn.net/lxk_1993/article/details/50511172 本文出自:[lxk_1993的博客]: 3个错误non-zero e ...
- 关于DOS与cmd(windows系统)
dos是计算机的最初期的操作系统,对电脑操作必须输入各种dos命令窗口,可以理解成运行计算机机器内部语言,知道编程吗?其实早期dos命令操作系统就是运行计算机内部的编程命令,因此操作人员都必须具有一定 ...
- 谈谈计算机上的那些存储器-Memory Hierarchy
文章首发于浩瀚先森博客http://www.guohao1206.com/2016/12/07/1248.html 说到计算机上的存储器,很多人第一反应是硬盘,然后是内存. 其实在计算机上除了硬盘和内 ...
- 我也来写:数据库访问类DBHelper
一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...
- 一个简单的Linq to TreeNode
最近两天写单元测试,碰到需要验证一个树是否是期望的,但是树这个结构要验证起来还真是有点烦... 我的树大概是这样的: class TreeNode<T> { ]; public TreeN ...
- java IO流复制图片
一.使用字节流复制图片 //字节流方法 public static void copyFile()throws IOException { //1.获取目标路径 //(1)可以通过字符串 // Str ...
- linux运维工作职责
(1)运维人员要谨记的6个字:运维人员做事需遵循:简单.易用.高效(2)运维人员服务的3大宗旨:1.企业数据安全保障.2.7*24小时业务持续提供服务.3.不断提升用户感受.体验.(3)初中级运维的 ...
- ajax(通过jQuery实现)
使用jQuery实现ajax相对来说方便一点,看w3cschool有几种实现的方法,我就总结一下自己以后会用到的几种方法 $.ajax方法: $.ajax方法里面有很多个参数可以使用,但我这里就写自己 ...