相关疑难解决方法(0)

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

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

我正在使用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)

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

python ordereddictionary

8
推荐指数
1
解决办法
5940
查看次数

标签 统计

ordereddictionary ×1

python ×1