gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:52 27 4
gpt4 key购买 nike

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

关于python - 'self.__class__.__missing__'是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1990145/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com