Python OrderedDict赢得';不要在一个类中排序

Python OrderedDict赢得';不要在一个类中排序,python,class,dictionary,ordereddictionary,Python,Class,Dictionary,Ordereddictionary,我有一个父类,我想保留它的子类的所有实例的注册表(以字典的形式)。简单,但我希望注册表根据其键进行排序,键是初始化时2个子类的参数。这是我的简化代码: from collections import OrderedDict class Parent: _registry = OrderedDict() def __init__(self): # add each sub-class instance to the registry & sort the

我有一个父类,我想保留它的子类的所有实例的注册表(以字典的形式)。简单,但我希望注册表根据其键进行排序,键是初始化时2个子类的参数。这是我的简化代码:

from collections import OrderedDict

class Parent:
    _registry = OrderedDict()
    def __init__(self):
        # add each sub-class instance to the registry & sort the registry
        self._registry.update({self._num:self})
        self._registry = OrderedDict(sorted(self._registry.items()))

class Foo(Parent):
    def __init__(self, number):
        self._num = number
        Parent.__init__(self)
        # then do some stuff

class Bar(Parent):
    def __init__(self, number):
        self._num = number
        Parent.__init__(self)
        # then do some other stuff
...
但是,尽管注册表使用新的子类对象进行自我更新,但它不会自行排序

>>> a = Foo(3)
>>> Parent._registry # check to see if a was added to the registry
OrderedDict([(3, <Foo instance at 0x00A19C0C8>)])
>>> b = Bar(1)
>>> Parent._registry # check to see if b was inserted before a in the registry
OrderedDict([(3, <Foo instance at 0x00A19C0C8>), (1, <Bar instance at 0x00A19C1C8>)])
为什么它不会自行排序?我需要它,因为以后,这些对象必须严格按照其
数量
参数的顺序发生变化。

这是因为:

self._registry = OrderedDict(sorted(self._registry.items()))
在实例上创建一个新属性,这不会影响
父项。\u registry

将该行替换为:

Parent._registry = OrderedDict(sorted(self._registry.items()))
这里
self.\u registry.items()
可以获取
Parent.\u registry
的值,但这并不意味着分配给
self.\u registry
将影响
Parent.\u registry


使用
self.\u注册表
本身的另一种方法:

def __init__(self):
    items = sorted(self._registry.items() + [(self._num, self)]) #collect items
    self._registry.clear() #clean the dict
    self._registry.update(items) #now update it

我还有一个类似的注册表问题,你能看一下吗?我没想到会有人这么快回答
def __init__(self):
    items = sorted(self._registry.items() + [(self._num, self)]) #collect items
    self._registry.clear() #clean the dict
    self._registry.update(items) #now update it