Skip to main content
 首页 » 编程设计

python之'self.__class__.__missing__'是什么意思

2025年05月04日20三少

在 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, 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.