Python __missing__
来源:互联网 发布:云计算 企业排名 编辑:程序博客网 时间:2024/06/09 22:09
According to the python documentation:
If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable.
For an example, see collections.defaultdict.
This is, at least, incomplete, since __missing__ must not only return the default value, but also assign it internally. This is made clear in the documentation for collections.defaultdict:
If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.
Surprisingly, the __missing__ method is not mentioned in the special method names section of the python documentation.
class memoize(dict): def __init__(self, func): self.func = func def __call__(self, *args): print "__call__" return self[args] def __missing__(self, key): print "__missing__" result = self[key] = self.func(*key) return result@memoizedef foo(a, b): return a * bprint foo(1,2)print foo(1,2)print foo(1,2)print foo(1,2)print foo(1,2)print foo(1,2)
执行结果:
__call____missing__2__call__2__call__2__call__2__call__2__call__2
- Python __missing__
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- YII带查询条件的分页问题解决
- java泛型类和泛型函数
- s3c2416 触摸屏驱动
- 如何做好一建考前复习
- AppCan与Testin联合解决Android 5.0兼容性问题
- Python __missing__
- 重载函数选择之谜
- C/C++变长参数宏(Variadic Macros)
- java设计模式
- 合理使用 inline来优化程序 尽可能减少临时对象 尽可能使用初始化列表
- 移动开发的十万个为什么?
- iOS中打印日志显示系统详细时间,类名,行号及打印值
- 淘宝杨志丰:OceanBase--淘宝结构化大数据解决之道
- android 获取listview checkbox选择的值