Null Object Design Pattern (Python recipe)
Null Object 个人感觉非常有用。也是在review公司其他同事写代码的时候看到。
当时使用了flask的request全局请求变量g,然后使用了g.x保存了一个东西。
当时在view代码读取g.x的时候震惊了,因为这一段代码并没有保存g.x,按道理来说应该是一个空值,当我拿着空值去调用其属性的时候应该会报AttributeError。
但是什么也没有发生,既没有报错,也没有发生什么,而且对其判断还是False,于是查看其实现才发现了这个。以下全部转自http://code.activestate.com/recipes/68205/
#!/user/bin/env python
# coding: utf-8
# {{{ http://code.activestate.com/recipes/68205/ (r1) """null.py This is a sample implementation of the 'Null Object' design pattern. Roughly, the goal with Null objects is to provide an 'intelligent'
replacement for the often used primitive data type None in Python or
Null (or Null pointers) in other languages. These are used for many
purposes including the important case where one member of some group
of otherwise similar elements is special for whatever reason. Most
often this results in conditional statements to distinguish between
ordinary elements and the primitive Null value. Among the advantages of using Null objects are the following: - Superfluous conditional statements can be avoided
by providing a first class object alternative for
the primitive value None. - Code readability is improved. - Null objects can act as a placeholder for objects
with behaviour that is not yet implemented. - Null objects can be replaced for any other class. - Null objects are very predictable at what they do. To cope with the disadvantage of creating large numbers of passive
objects that do nothing but occupy memory space Null objects are
often combined with the Singleton pattern. For more information use any internet search engine and look for
combinations of these words: Null, object, design and pattern. Dinu C. Gherman,
August 2001
""" class Null(object): """A class for implementing Null objects. This class ignores all parameters passed when constructing or
calling instances and traps all attribute and method requests.
Instances of it always (and reliably) do 'nothing'. The code might benefit from implementing some further special
Python methods depending on the context in which its instances
are used. Especially when comparing and coercing Null objects
the respective methods' implementation will depend very much
on the environment and, hence, these special methods are not
provided here.
""" # object constructing def __init__(self, *args, **kwargs):
"Ignore parameters."
return None # object calling def __call__(self, *args, **kwargs):
"Ignore method calls."
return self def next(self):
raise StopIteration def __len__(self):
return 0 def __eq__(self, other):
return self is other # misc. def __repr__(self):
"Return a string representation."
return "<Null>" def __str__(self):
"Convert to a string and return it."
return "" def default(self):
return "" def __nonzero__(self):
return False def for_json(self):
return '' __sub__ = __div__ = __mul__ = __floordiv__ = __mod__ = __and__ = __or__ = \
__xor__ = __rsub__ = __rdiv__ = __rmul__ = __rfloordiv__ = __rmod__ = \
__rand__ = __rxor__ = __ror__ = __radd__ = __pow__ = __rpow__ = \
__rshift__ = __lshift__ = __rrshift__ = __rlshift__ = __truediv__ = \
__rtruediv__ = __add__ = __getitem__ = __neg__ = __pos__ = __abs__ = \
__invert__ = __setattr__ = __getattr__ = __delattr__ = __delitem__ = __setitem__ = \
__iter__ = __call__ Null = Null()
这里我们在其他地方引用的时候可以直接从这个文件里引入Null,在需要的时候返回这个Null对象实例就可以了。
Reference:
http://code.activestate.com/recipes/68205/ ---Null Object Design Pattern (Python recipe)
Null Object Design Pattern (Python recipe)的更多相关文章
- python singleton design pattern super() 多继承
python singleton design pattern decorate baseclass metaclass import module super() 一.A decorator de ...
- 设计模式:空对象模式(Null Object Pattern)
设计模式:空对象模式(Null Object Pattern) 背景 群里聊到<ASP.NET设计模式>,这本书里有一个“Null Object Pattern”,大家就闲聊了一下这个模式 ...
- 被遗忘的设计模式——空对象模式(Null Object Pattern)
GoF(四人帮)那本<设计模式 可复用面向对象软件的基础>可谓是设计模式方面的经典之作,其中介绍的23种设计模式, 也可谓是经典中的经典.但是,设计模式的种类绝不仅仅是这23种,除此之外还 ...
- Java 空对象设计模式(Null Object Pattern) 讲解
转自:http://www.cnblogs.com/haodawang/articles/5962531.html 有时候我们的代码中为避免 NullPointerException 会出现很多的对N ...
- Page Object Model (Selenium, Python)
时间 2015-06-15 00:11:56 Qxf2 blog 原文 http://qxf2.com/blog/page-object-model-selenium-python/ 主题 Sel ...
- Thinking In Design Pattern——MVP模式演绎
原文<Thinking In Design Pattern——MVP模式演绎>不知为何丢失了,故重新整理了一遍. 目录 What Is MVP Domain Model StubRepos ...
- [Java] Design Pattern:Code Shape - manage your code shape
[Java] Design Pattern:Code Shape - manage your code shape Code Shape Design Pattern Here I will intr ...
- Chain Of Responsibility Design Pattern Example
Avoid coupling the sender of a request to the receiver by giving more than one object a chance to ha ...
- java设计模式大全 Design pattern samples in Java(最经典最全的资料)
java设计模式大全 Design pattern samples in Java(最经典最全的资料) 2015年06月19日 13:10:58 阅读数:11100 Design pattern sa ...
随机推荐
- Qt+Qgis二次开发:在状态条显示当前鼠标坐标
1 概述 鼠标在地图上移动,需要实时获取当前坐标位置.2 原理 从当前位置获取视口坐标后,实时转换为地图坐标.3 方法 处理鼠标位置,必须获取鼠标的当前坐标.但是Qt的鼠标事件由QgsMapCanv ...
- 分析网络流量Capsa笔记
Capsa是一款网络分析仪,允许您监控网络流量,解决网络问题并分析数据包.通过提供生动的图表,通过设计良好的GUI提供丰富的统计信息和实时警报,Capsa可让IT管理员实时识别,诊断和解决有线和无线网 ...
- 4.1《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)—目录结构
Unix风格的目录结构通常使用一个目录名列表并用正斜杠分隔来表示,这样我们可以结合ls命令: $ ls /Users/mhartl/ruby 或者 $ ls /usr/local/bin 正如图20, ...
- CF1070L Odd Federalization 高斯消元
传送门 \(r = 1\)直接判断所有点度数是否为偶数 考虑\(r = 2\)的情况.设\(x_i=0/1\)表示\(i\)点所在的集合,那么若\(2 \mid du_u\),则\(\bigoplus ...
- 扫描shader
游戏中经常需要制作出白光扫描的效果,这道光在透明区域不会显示.如果用图片叠加可能透明区域不太好处理,这里可通过shader实现. Shader "Custom/LogoShader" ...
- Object-Oriented(二)原型对象
自用备忘笔记 1. 理解原型对象 只要创建函数,函数上就会创建一个 prototype 属性指向函数的原型对象. function Person() {} Person.prototype //指向该 ...
- C#_XML与Object转换
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.X ...
- 大话重构连载15:采用Mock技术完成测试
第五次重构我们引入了数据库的设计,用户信息要从数据库中读取,问候语库存储在数据库中,并支持添加与更新.数据库的引入使自动化测试变得困难了,因为数据状态总是变化着的,而这种变化使得测试过程不能复现,这是 ...
- devstack 安装(centos7)
1. 创建devstack用户 sudo useradd -s /bin/bash -d /opt/stack -m stackecho "stack ALL=(ALL) NOPASSWD: ...
- python基础学习笔记(四)
列表 本节继续讨论列表不同元组和字符串的地方:列表是可变的(mutable)----可以改变列表的内容,并且列表有很多有用的.专门的方法. List函数可以将一个字符串拆分成列表. >>& ...