如何子类化OrderedDict? [英] How to subclass an OrderedDict?

查看:136
本文介绍了如何子类化OrderedDict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Subclassing a Python dict works as expected:

>>> class DictSub(dict):
...     def __init__(self):
...         self[1] = 10
...         
>>> DictSub()
{1: 10}

然而,用一个<做同样的事情code> collections.OrderedDict 不起作用:

However, doing the same thing with a collections.OrderedDict does not work:

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

因此,OrderedDict实现使用私有 __ root 属性,这可以防止子类 OrdDictSub 表现得像 DictSub 子类。为什么?怎样才能从OrderedDict继承?

Thus, the OrderedDict implementation uses a private __root atribute, which prevents the subclass OrdDictSub from behaving like the DictSub subclass. Why? How can one inherit from an OrderedDict?

推荐答案

你需要调用 OrderedDict .__ init __ 来自你的 __ init __

class OrdDictSub(collections.OrderedDict):
    def __init__(self):
        super(OrdDictSub, self).__init__()

你没有给 OrderedDict 一个初始化自己的机会。从技术上讲,您也希望为 dict 子类执行此操作,因为您需要完全初始化的 dict dict 在没有它的情况下工作的事实只是运气。

You haven't given OrderedDict a chance to initialize itself. Technically, you want to do this for your dict subclass as well, since you want a fully initialized dict. The fact that dict works without it is just luck.

这篇关于如何子类化OrderedDict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆