Python OrderedDict重新初始化:订单丢失

Python OrderedDict重新初始化:订单丢失,python,ordereddictionary,Python,Ordereddictionary,我的类是从OrderedDict继承的,我想重新初始化字典。但下面的简化代码仅更改键的值-元素的顺序保持不变: from collections import OrderedDict class Example(OrderedDict): def __init__(self,d): OrderedDict.__init__(self,d) #something that should be done only once - at instance cre

我的类是从OrderedDict继承的,我想重新初始化字典。但下面的简化代码仅更改键的值-元素的顺序保持不变:

from collections import OrderedDict

class Example(OrderedDict):
    def __init__(self,d):
        OrderedDict.__init__(self,d)
        #something that should be done only once - at instance creation

    def reinit(self,d):
        OrderedDict.__init__(self,d)

d=Example([(1,1),(2,2)])
d.reinit([(2,20),(1,10)])

print(d) #Example([(1, 10), (2, 20)])
所以问题是:
OrderedDict.\uuuu init\uuuuu
内部发生了什么?它应该以这种方式工作吗

OrderedDict.\uuu init\uuuu()
不会清除字典。它只使用了相当于
self.update()
的方法将元素添加到字典中。您所做的只是添加已经存在的密钥

您必须首先删除这些键或清除字典:

def reinit(self, d):
    self.clear()
    OrderedDict.__init__(self, d)
演示:

您可以随时查看大多数Python库模块的源代码;这些链接将您链接到

>>> from collections import OrderedDict
>>> class Example(OrderedDict):
...     def reinit(self, d):
...         self.clear()
...         OrderedDict.__init__(self, d)
... 
>>> d=Example([(1,1),(2,2)])
>>> d.reinit([(2,20),(1,10)])
>>> print(d)
Example([(2, 20), (1, 10)])