从OrderedDict和defaultdict继承 [英] subclassing from OrderedDict and defaultdict

查看:304
本文介绍了从OrderedDict和defaultdict继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Raymond Hettinger 显示了一种非常酷的结合集合类的方法:

Raymond Hettinger showed a really cool way to combine collection classes:

from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
  pass
# if pickle support is desired, see original post

我想对OrderedDict和defaultdict做类似的操作。但是,当然,defaultdict有一个不同的 __ init __ 签名,所以它需要额外的工作。什么是最清洁的方式来解决这个问题?我使用Python 3.3。

I want to do something similar for OrderedDict and defaultdict. But of course, defaultdict has a different __init__ signature, so it requires extra work. What's the cleanest way to solve this problem? I use Python 3.3.

我在这里找到了一个很好的解决方案: http:/ /stackoverflow.com/a/4127426/336527 ,但我想是可能从defaultdict派生可能会使这更简单吗?

I found a good solution here: http://stackoverflow.com/a/4127426/336527, but I was thinking maybe deriving from defaultdict might make this even simpler?

推荐答案

从您链接的答案中继承 OrderedDict 是最简单的方法。

Inheriting from OrderedDict as in the answer you linked to is the simplest way. It is more work to implement an ordered store than it is to get default values from a factory function.

所有你需要实现的 defaultdict 是一些自定义的 __ init __ 逻辑和非常简单的 __ missing __

All you need to implement for defaultdict is a bit of custom __init__ logic and the extremely simple __missing__.

如果你继承 defaultdict ,你必须委托或重新实现 __ setitem __ __ delitem __ __ iter __ ,以重现按序操作。您仍然必须在 __ init __ 中进行设置工作,但您可能可以继承或根据您的需要省略一些其他方法。

If you instead inherit from defaultdict, you have to delegate to or re-implement at least __setitem__, __delitem__ and __iter__ to reproduce the in-order operation. You still have to do setup work in __init__, though you might be able to inherit or simply leave out some of the other methods depending on your needs.

查看原始食谱任何其他人链接到从另一个Stack Overflow问题

这篇关于从OrderedDict和defaultdict继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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