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

标签 python ordereddictionary

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

我正在使用 odict来自 PEP 372 的类(class),但我想将其用作 __dict__ 成员,即:

class Bag(object):
    def __init__(self):
        self.__dict__ = odict()

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

>>> b = Bag()
>>> b.apple = 1
>>> b.apple
1
>>> b.banana = 2
>>> b.banana
2

但是尝试访问实际的字典是行不通的:

>>> b.__dict__.items()
[]
>>> b.__dict__
odict.odict([])

它变得更奇怪了:

>>> b.__dict__['tomato'] = 3
>>> b.tomato
3
>>> b.__dict__
odict.odict([('tomato', 3)])

我觉得自己很蠢。你能帮帮我吗?

最佳答案

我能找到的最接近您问题的答案是 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)])

关于python - 在 python 中使用有序字典作为对象字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455059/

相关文章:

Python - 根据条件找到最大值

python - 插入字节类型的对象

python - 在笛卡尔坐标系中计算不规则形状的边界 2D

c# - 如何按值对字典条目列表进行排序(自定义排序)

Python - OrderedDict 中的字典理解不起作用

带有案例的 Python map()

python - 有什么方法可以将 Scapy Packet 中的字段链接到构建的 str 中的部分吗?

python - 有什么理由不使用 OrderedDict?

python - 在 pytorch 中训练期间 best_state 随模型变化

python - 重命名字典键