开发者

Is there any difference between UserDict and Dict?

If I want a class to have a dictionary behavior, why should I inherit from dict 开发者_Go百科or UserDict?


You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __getitem__ will not be used by get unless you also override that one, and so on, and so forth.

The UserDict.DictMixin mix-in goes back a lot further and lets you implement just a few methods: the other methods, as supplied by the mix-in, will pick up and use your own overrides. Note, however, from the docs:

Starting with Python version 2.6, it is recommended to use collections.MutableMapping instead of DictMixin.

The new ABCs (Abstract Base Classes) in the collections module have much the same advantages as good old UserDict.DictMixin, wider applicability, and more regularity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜