dictionary,那么只要我们定义__missing__函数,当 key 不存在时,这个函数会以 key 做为
参数被调用,我们试验一下。
1
class
myDict(dict):
2
def
__missing__
(self, key):
3
"__missing__ called , key = "
, key
4 return "^_^"
然后打开
Python 命令行解释器,import mdict
>>>
from
mdict
import
myDict
>>> d = myDict({1:
'a'
, 2:
'b'
, 3:
'c'
})
>>> d
{1:
'a'
, 2:
'b'
, 3:
'c'
}
>>> d[1]
'a'
>>> d[4]
__missing__
called , key = 4
^_^
可以看到
__missing__()被调用了。
如果只想得到某个
key 对应的 value,不想对其进行改变,则用类方法 get() ,这类似 C++中
“引用”和“值”的概念。
>>> a = d.get(1)
>>> a
'a'
2.2 类方法实现的操作
>>>d.clear() #清空
>>>d.copy() #拷贝生成另一个,浅拷贝(shallow copy)