博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Null Object Design Pattern (Python recipe)
阅读量:5293 次
发布时间:2019-06-14

本文共 3667 字,大约阅读时间需要 12 分钟。

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.pyThis 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 orNull (or Null pointers) in other languages. These are used for manypurposes including the important case where one member of some groupof otherwise similar elements is special for whatever reason. Mostoften this results in conditional statements to distinguish betweenordinary 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 passiveobjects that do nothing but occupy memory space Null objects areoften combined with the Singleton pattern.For more information use any internet search engine and look forcombinations 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 "
" 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)

转载于:https://www.cnblogs.com/piperck/p/5662882.html

你可能感兴趣的文章
移动应用开发选型:向左还是向右?
查看>>
开发进度一
查看>>
十天冲刺(6)
查看>>
加载selenium2Library失败---robotframework环境搭建(site-packages下无selenium2library文件夹)...
查看>>
MyBaits学习
查看>>
实体标签,媒体标签,飘动标签
查看>>
MySQL安装的详细步骤
查看>>
pat1121-1131
查看>>
AtCoder Regular Contest 101 D - Median of Medians
查看>>
小贾学习设计模式笔记-----------工厂模式(一)
查看>>
Deformity JSP Webshell、Webshell Hidden Learning
查看>>
centos7 更改ip
查看>>
C程序实现快速从文件输入和输出到文件
查看>>
vi 常用命令行
查看>>
C语言 将小写字母写入文件
查看>>
Phalcon Framework的MVC结构及启动流程分析
查看>>
ACWING_802_区间和
查看>>
python学习手册笔记——14.迭代器和解析
查看>>
jQuery Ajax
查看>>
根据XML文件生成XSD文件
查看>>