哪里有好的null object pattern应用实例,pattern应用实例,null object
哪里有好的null object pattern应用实例,pattern应用实例,null object
null object python是一个设计模式,python实现如下,此模式是想减少无必要的is null逻辑判断,不过没能想到具体怎么应用在项目或者自己的代码中,希望有个应用的实例代码,thanks。
#!/usr/bin/env python# -*- coding: utf-8 -*-"""http://code.activestate.com/recipes/68205-null-object-design-pattern/"""class Null: def __init__(self, *args, **kwargs): """Ignore parameters.""" return None def __call__(self, *args, **kwargs): """Ignore method calls.""" return self def __getattr__(self, mname): """Ignore attribute requests.""" return self def __setattr__(self, name, value): """Ignore attribute setting.""" return self def __delattr__(self, name): """Ignore deleting attributes.""" return self def __repr__(self): """Return a string representation.""" return "<Null>" def __str__(self): """Convert to a string and return it.""" return "Null"def test(): """Perform some decent tests, or rather: demos.""" # constructing and calling n = Null() print(n) n = Null('value') print(n) n = Null('value', param='value') print(n) n() n('value') n('value', param='value') print(n) # attribute handling n.attr1 print('attr1', n.attr1) n.attr1.attr2 n.method1() n.method1().method2() n.method('value') n.method(param='value') n.method('value', param='value') n.attr1.method1() n.method1().attr1 n.attr1 = 'value' n.attr1.attr2 = 'value' del n.attr1 del n.attr1.attr2.attr3 # representation and conversion to a string assert repr(n) == '<Null>' assert str(n) == 'Null'if __name__ == '__main__': test()### OUTPUT #### Null# Null# Null# Null# attr1 Null
编橙之家文章,
相关内容
- pyqt点击按钮无响应如何调整,pyqt点击按钮响应,如图:
- 配置好的python编译环境,却找不到sublime类是为什么?,
- Python django AutoField从2开始的前提条件蛤是什么,django
- python伪静态异常跳转后就失败,python伪静态跳转,<I
- 请问我的python AVL树这样号写对不对,,class Node(o
- Debian Python程序,用mplayer能实现渐变效果吗?,pythonmplay
- 有经验的Python大师帮看看CRC16代码实现过程错误在哪里
- Python请问PIL渲染小字号汉字截断现象怎么解决,python
- python mongoengine条件查询比较字段方法求助,pythonmongoe
- Pyhton能为视频地址解析做优化吗,pyhton能为视频解析
评论关闭