python - Inheriting from defaultddict and OrderedDict -
i have tried inheriting both collections.defaultdict , collections.ordereddict so:
class ordereddefaultdict(defaultdict, ordereddict): pass and so:
class ordereddefaultdict(ordereddict, defaultdict): pass in order created ordered default dict (a class should remember order in new default items generated) seems throw error stating:
typeerror: multiple bases have instance lay-out conflict i have read here it's because they're both implemented in c. upon disabling python's c implementation of ordereddict commenting section in collections module:
try: _collections import ordereddict except importerror: # leave pure python version in place. pass i have managed inherit both, not seem work expected. have 2 questions then:
- why can't inherit 2 classes written in c? understand if wouldn't able inherit class written in c why can inherit 1 , not 2?
- implementing requested class easy subclassing
ordereddict, overriding__getitem__()matchdefaultdict's behavior. is there better way (preferably within standard library) mimick same behavior? or subclassingordereddictoptimal? (subclassingdefaultdictpossible implementing is easier usingordereddict)
the first question important of two implementing myself subclassing ordereddict shouldn't pose problem.
the functionality of defaultdict can implemented defining __missing__ method:
class defaultordereddict(ordereddict): def __init__(self, default_factory=none, **kwargs): ordereddict.__init__(self, **kwargs) self.default_factory = default_factory def __missing__(self, key): result = self[key] = self.default_factory() return result
Comments
Post a Comment