相关疑难解决方法(0)

像属性一样访问dict键?

我发现访问dict密钥更加方便,obj.foo而不是obj['foo'],所以我写了这个代码片段:

class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value
Run Code Online (Sandbox Code Playgroud)

但是,我认为必须有一些原因,Python不提供开箱即用的功能.以这种方式访问​​dict密钥有什么警告和陷阱?

python syntax dictionary

273
推荐指数
16
解决办法
16万
查看次数

如何子类化OrderedDict?

对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继承?

python inheritance subclass ordereddictionary

28
推荐指数
1
解决办法
5285
查看次数