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
没有它的事实就是运气.