如何子类化OrderedDict?

Eri*_*got 28 python inheritance subclass ordereddictionary

对Python进行子类化dict按预期工作:

>>> class DictSub(dict):
...     def __init__(self):
...         self[1] = 10
...         
>>> DictSub()
{1: 10}
Run Code Online (Sandbox Code Playgroud)

但是,用a做同样的事情是collections.OrderedDict行不通的:

>>> import collections
>>> class OrdDictSub(collections.OrderedDict):
...     def __init__(self):
...         self[1] = 10
...         
>>> OrdDictSub()
(…)
AttributeError: 'OrdDictSub' object has no attribute '_OrderedDict__root'
Run Code Online (Sandbox Code Playgroud)

因此,OrderedDict实现使用私有__root属性,这可以防止子类OrdDictSub的行为类似于DictSub子类.为什么?如何从OrderedDict继承?

Ned*_*der 35

你需要OrderedDict.__init__从你的__init__:

class OrdDictSub(collections.OrderedDict):
    def __init__(self):
        super(OrdDictSub, self).__init__()
Run Code Online (Sandbox Code Playgroud)

你没有OrderedDict机会初始化自己.从技术上讲,您也希望为dict子类执行此操作,因为您需要完全初始化dict.dict没有它的事实就是运气.

  • 你不想在init中使用args和kwargs吗?`def __init __(self,*args,**kwargs):super(OrdDictSub,self).__ init __(*args,**kwargs)` (6认同)