부모 클래스가 있고 해당 하위 클래스의 모든 인스턴스에 대한 레지스트리 (사전 형식)를 유지하려고합니다. 간단하지만 레지스트리가 초기화에 대한 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
비슷한 종류의 레지스트리에 또 다른 문제가 있습니다. 어떻게 보셨겠습니까? http://stackoverflow.com/questions/26726609/function-wont-sucessfully-loop-over-class-instances-unless-contents-entered-man – binaryfunt
누군가가 그렇게 빨리 대답 할 것으로 기대하지 않았다고 생각하다. – binaryfunt