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 ...
随机推荐
- MySQL主从同步原理
mysql主从复制用途 实时灾备,用于故障切换 读写分离,提供查询服务 备份,避免影响业务 主从部署必要条件 主库开启binlo日志(设置log-bin参数) 主从server-id不同 从库可以连同 ...
- Linux Sysstat性能监控工具安装及常见8个命令使用例子
Sysstat,一种常用在Linux系统服务器中的软件工具包,可以用来监控服务器的性能.比如可以监控CPU.硬盘.网络等数据,我们可以用来进行分析服务器的性能和资源的使用效率.老左将在这篇文章中学习. ...
- VsCode语言设置为中文
一.安装插件 二.Ctrl+shift+p 搜索Configure Display Language 三.修改locale.json { // Defines VS Code's display la ...
- QT中子目录调用另一个子目录
解决办法: 第一:建立一个subdirs项目,子项目管理 第二:添加二个子项目例如:A子项目 B子项目 第三:现在A子项目调用 B子项目 在A子项目中:右键>添加库>内部库(把A添加进 ...
- MATLAB常用快捷键命令总结
1. 在命令窗口(Command Window)中: 1)[↑.↓]——切换到之前.之后运行过的命令,可以重复按多次来达到你想要的命令: 2)[Tab]——自动补全.在command窗口,输入一个命令 ...
- 百度云受邀成为 LF Edge 创始成员
导读 1月24日,Linux Foundation(Linux基金会,以下简称LF)宣布正式成立旗下子机构边缘计算基金会LF Edge,旨在建立边缘计算统一开源框架.百度云受邀成为创始成员. 中国公司 ...
- 深入浅出的webpack构建工具--webpack4+vue+router项目架构(十四)
阅读目录 一:vue-router是什么? 二:vue-router的实现原理 三:vue-router使用及代码配置 四:理解vue设置路由导航的两种方法. 五:理解动态路由和命名视图 六:理解嵌套 ...
- Android学习之基础知识十三 — 四大组件之服务详解第二讲(完整版的下载示例)
上一讲学习了很多关于服务的使用技巧,但是当在真正的项目里需要用到服务的时候,可能还会有一些棘手的问题让你不知所措.接下来就来综合运用一下,尝试实现一下在服务中经常会使用到的功能——下载. 在这一讲我们 ...
- Android学习之基础知识四-Activity活动6讲(体验Activity的生命周期)
一.体验活动的生命周期的执行 代码组成: 1.三个Java类:MainActivity.java.NormalActivity.java.DialogActivity.java 2.三个布局文件:ac ...
- nginx-haproxy-lvs功能和性能对比 nginx - max-fail + 调度算法
优点(性能和功能两方面分析) 缺点 lvs 工作在4层,可以对http,MySQL等服务负载均衡.负责流量的分发,对io,cpu,mem的消耗少 功能比较少,没有正则匹配的功能 nginx 工作在7层 ...