what is the 'self.__class__.__missing__' mean
in pinax Userdict.py:
def __getitem__(self, key):
if key in self.data:
return self.data[key]
if hasattr(self.__class__, "__missing__"):
return self.__class__.__missing__(self, key)
why does it do this on self开发者_运维技巧.__class__.__missing__
.
thanks
The UserDict.py presented here emulates built-in dict
closely, so for example:
>>> class m(dict):
... def __missing__(self, key): return key + key
...
>>> a=m()
>>> a['ciao']
'ciaociao'
just as you can override the special method __missing__
to deal with missing keys when you subclass the built-in dict
, so can you override it when you subclass that UserDict
.
The official Python docs for dict are here, and they do say:
New in version 2.5: If a subclass of dict defines a method
__missing__
(), if the key key is not present, thed[key]
operation calls that method with the key key as argument. Thed[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, seecollections.defaultdict
.
If you want to use default values in a dict (aka __missing__), you can check out defaultdict
from collections module:
from collections import defaultdict
a = defaultdict(int)
a[1] # -> 0
a[2] += 1
a # -> defaultdict(int, {1: 0, 2: 1})
精彩评论