My first attempt to combine the features of two dictionaries in the collections
module was to create a class that inherits them:
from collections import OrderedDict, defaultdict
class DefaultOrderedDict(defaultdict, OrderedDict):
def __init__(self, default_factory=None, *a, **kw):
super().__init__(default_factory, *a, **kw)
However, I cannot assign an item to this dictionary:
d = DefaultOrderedDict(lambda: 0)
d['a'] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.3/collections/__init__.py", line 64, in __setitem__
self.__map[key] = link = Link()
AttributeError: 'DefaultOrderedDict' object has no attribute '_OrderedDict__map'
Indeed, this question about how to create a similar object has answers that achieve it by extending the OrderedDict
class and manually re-implementing the additional methods provided defaultdict
. Using multiple inheritance would be cleaner. Why doesn't it work?