[英]OrderedDict won't sort within a class
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! b
来后a
注册表!
If I do it manually in the iPython console, it works: 如果我在iPython控制台中手动执行此操作,则它会起作用:
>>> 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. 我需要这样做,因为稍后,必须按照number
参数的严格顺序对这些对象进行处理。
That's because: 那是因为:
self._registry = OrderedDict(sorted(self._registry.items()))
creates a new attrbute on the instance, this doesn't affect Parent._registry
. 在实例上创建一个新属性,这不会影响Parent._registry
。
Replace that line with: 将该行替换为:
Parent._registry = OrderedDict(sorted(self._registry.items()))
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.items()
可以获取的价值Parent._registry
但是,这并不意味着分配给self._registry
会影响Parent._registry
。
Another way to do it using self._registry
itself: 使用self._registry
本身的另一种方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.