简体   繁体   English

从OrderedDict和defaultdict继承子类

[英]subclassing from OrderedDict and defaultdict

Raymond Hettinger showed a really cool way to combine collection classes: Raymond Hettinger 展示了一种非常酷的方式来组合集合类:

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

I want to do something similar for OrderedDict and defaultdict. 我想为OrderedDict和defaultdict做类似的事情。 But of course, defaultdict has a different __init__ signature, so it requires extra work. 但是,当然,defaultdict具有不同的__init__签名,因此需要额外的工作。 What's the cleanest way to solve this problem? 解决这个问题最简洁的方法是什么? I use Python 3.3. 我使用Python 3.3。

I found a good solution here: https://stackoverflow.com/a/4127426/336527 , but I was thinking maybe deriving from defaultdict might make this even simpler? 我在这里找到了一个很好的解决方案: https//stackoverflow.com/a/4127426/336527 ,但我想可能从defaultdict中获得可能会使这更简单?

Inheriting from OrderedDict as in the answer you linked to is the simplest way. 在链接到的答案中继承OrderedDict是最简单的方法。 It is more work to implement an ordered store than it is to get default values from a factory function. 实现有序存储比从工厂函数获取默认值要多得多。

All you need to implement for defaultdict is a bit of custom __init__ logic and the extremely simple __missing__ . 你需要为defaultdict实现的是一些自定义__init__逻辑和非常简单的__missing__

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. 如果你改为从defaultdict继承,你必须委托或重新实现至少__setitem__ __iter____iter__ __delitem____iter__来重现顺序操作。 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. 您仍然需要在__init__进行设置工作,尽管您可能可以继承或根据您的需要省略其他一些方法。

Take a look at the original recipe or any of the others linked to from another Stack Overflow question for what that would entail. 查看原始配方其他任何与其他Stack Overflow问题相关联的问题 ,了解其中包含的内容。

I've found a way to subclass them both, but not sure if there are bugs: 我找到了一种方法来对它们进行子类化,但不确定是否存在错误:

class OrderedDefaultDict(defaultdict, OrderedDict):
    def __init__(self, default, *args, **kwargs):
        defaultdict.__init__(self, default)
        OrderedDict.__init__(self, *args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM