subclassing from OrderedDict and defaultdict

后端 未结 2 670
广开言路
广开言路 2021-02-14 03:59

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

from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict)         


        
相关标签:
2条回答
  • 2021-02-14 04:05

    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)
    
    0 讨论(0)
  • 2021-02-14 04:09

    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.

    All you need to implement for defaultdict is a bit of custom __init__ logic and the extremely simple __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. 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.

    Take a look at the original recipe or any of the others linked to from another Stack Overflow question for what that would entail.

    0 讨论(0)
提交回复
热议问题