2
我有一個父類,我想保留其子類的所有實例的註冊表(以字典的形式)。很簡單,但我希望註冊表根據其鍵進行排序,這是初始化時兩個子類的參數。這是我的代碼簡化形式:OrderedDict不會在一個類中排序
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>)])
b
進來註冊表a
後!
如果我在IPython的控制檯做手工,它的工作原理:
>>> Parent._registry = OrderedDict(sorted(Parent._registry.items()))
OrderedDict([(1, <Bar instance at 0x00A19C1C8>), (3, <Foo instance at 0x00A19C0C8>)])
爲什麼不會是那種本身?我需要它,因爲以後,事情必須發生在這些對象上,嚴格按照他們的number
參數。
啊感謝。掌握OOP ... – binaryfunt 2014-11-03 22:56:06
我有類似註冊表的另一個問題,你認爲你可以看看嗎? http://stackoverflow.com/questions/26726609/function-wont-sucessfully-loop-over-class-instances-unless-contents-entered-man – binaryfunt 2014-11-04 02:10:21
劃痕,沒想到有人回答如此之快 – binaryfunt 2014-11-04 02:16:03