OrderedDict不会在类中排序 [英] OrderedDict won't sort within a class

查看:105
本文介绍了OrderedDict不会在类中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类,我想要保持其子类的所有实例的注册表(以字典的形式)。很容易,但我想注册表根据自己的键排序,这是初始化的2个子类的参数。这是我的代码以简化的形式:

I have a parent class, and I want to keep a registry (in the form of a dictionary) of all instances of its sub-classes. Easy, but I want the registry to sort itself based on its keys, which are the arguments of the 2 sub-classes on initialisation. This is my code in simplified form:

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
...

但是,尽管注册表使用新的子类对象,它不会自己排序。

But, although the registry updates itself with the new sub-class objects, it does not sort itself.

>>> 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>)])
b comes after a in the registry!

如果我在iPython控制台中手动执行,它的工作原理:

If I do it manually in the iPython console, it works:

>>> Parent._registry = OrderedDict(sorted(Parent._registry.items()))
OrderedDict([(1, <Bar instance at 0x00A19C1C8>), (3, <Foo instance at 0x00A19C0C8>)])

为什么不排序?我需要它,因为以后,事情必须发生在这些对象严格的顺序他们数字参数。

Why won't it sort itself? I need it to, because later on, things have to happen to those objects in strict order of their number arguments.

推荐答案

这是因为:

self._registry = OrderedDict(sorted(self._registry.items()))

在实例上创建一个新的attrbute, c $ c> Parent._registry 。

creates a new attrbute on the instance, this doesn't affect Parent._registry.

将此行替换为:

Parent._registry = OrderedDict(sorted(self._registry.items()))

这里 self._registry.items()可以获取 Parent._registry 的值, self._registry 的作业将影响 Parent._registry

Here self._registry.items() can fetch the value of Parent._registry but that doesn't mean assignment to self._registry will affect Parent._registry.

使用 self._registry 本身的另一种方法:

Another way to do it using self._registry itself:

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

这篇关于OrderedDict不会在类中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆