问题描述:

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)

Which however produces:

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

Of course I could still make a working program using:

raise KeyError(key)

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.

网友答案:

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.

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)
网友答案:

subclass from collections.defaultdict which already features a missing method.

https://docs.python.org/3/library/collections.html#collections.defaultdict

__missing__(key)

If the default_factory attribute is None, this raises a KeyError exception with the key as argument.

If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

If calling default_factory raises an exception this exception is propagated unchanged.

This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().

Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

相关阅读:
Top