我怎么能从字典中称呼__missing__ [英] How can I call __missing__ from dict

查看:89
本文介绍了我怎么能从字典中称呼__missing__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从dict派生并覆盖缺少的方法.我想做一些事情,然后仍然调用它的超级功能.像这样:

I would like to derive from dict and overwrite the method missing. I would like to do some stuff and then still call its super function. Something like this:

class Foo(dict):
    def __missing__(self, key):
        print('missing {}'.format(key))
        return super().__missing__(key)

但是会产生:

AttributeError: 'super' object has no attribute '__missing__'

当然我仍然可以使用以下方法制作一个工作程序:

Of course I could still make a working program using:

raise KeyError(key)

但是我更愿意称其为超级功能.因为代码可以(或者可能会在未来的python版本中)在super().__missing__中执行,而不是引发KeyError.

But I would much rather call the super function. Because code could (or maybe at a future version of python will be) executed in super().__missing__ other than raising the KeyError.

推荐答案

没有dict.__missing__;只需将呼叫放到super().__missing__(并调出KeyError).该方法是可选,并且没有默认实现.

There is no dict.__missing__; just drop the call to super().__missing__ (and raise a KeyError). The method is optional and has no default implementation.

或者,如果您想正确地支持多重继承,则可以捕获AttributeError异常:

Alternatively, if you want to support multiple inheritance properly, you could catch the AttributeError exception:

class Foo(dict):
    def __missing__(self, key):
        print('missing {}'.format(key))
        try:
            return super().__missing__(key)
        except AttributeError:
            raise KeyError(key)

这篇关于我怎么能从字典中称呼__missing__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆