在python中使用有序的dict作为对象字典

its*_*dok 8 python ordereddictionary

我不知道为什么这不起作用:

我正在使用PEP 372中odict类,但我想将它用作成员,即:__dict__

class Bag(object):
    def __init__(self):
        self.__dict__ = odict()
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,我得到了奇怪的结果.这有效:

>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2
Run Code Online (Sandbox Code Playgroud)

但是尝试访问实际的字典不起作用:

>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])
Run Code Online (Sandbox Code Playgroud)

它变得更奇怪了:

>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])
Run Code Online (Sandbox Code Playgroud)

我感觉非常愚蠢.你能帮我吗?

syk*_*ora 8

我能找到的最接近你问题的答案是http://mail.python.org/pipermail/python-bugs-list/2006-April/033155.html.

基本上,如果__dict__不是实际的dict(),则忽略它,并且属性查找失败.

另一种方法是使用odict作为成员,并相应地覆盖getitem和setitem方法.

>>> class A(object) :
...     def __init__(self) :
...             self.__dict__['_odict'] = odict()
...     def __getattr__(self, value) :
...             return self.__dict__['_odict'][value]
...     def __setattr__(self, key, value) :
...             self.__dict__['_odict'][key] = value
... 
>>> a = A()
>>> a
<__main__.A object at 0xb7bce34c>
>>> a.x = 1
>>> a.x
1
>>> a.y = 2
>>> a.y
2
>>> a.odict
odict.odict([('x', 1), ('y', 2)])
Run Code Online (Sandbox Code Playgroud)