在 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)
为什么它在 self.__class__.__missing__ 上执行此操作。
谢谢
请您参考如下方法:
UserDict.py 呈现 here模拟内置 dict紧密地,例如:
>>> class m(dict):
... def __missing__(self, key): return key + key
...
>>> a=m()
>>> a['ciao']
'ciaociao'
就像你可以覆盖特殊方法一样__missing__在子类化内置 dict 时处理丢失的键,所以当你将 UserDict 子类化时你可以覆盖它吗? .
dict 的官方 Python 文档是 here ,他们确实说:
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,KeyErroris raised.__missing__()must be a method; it cannot be an instance variable. For an example, seecollections.defaultdict.
