Mein Problem erstellen ist:Python, wie verschiedene Instanzen derselben Klasse in eine Iteration
Ich mag eine Composite-Klasse Objekte Blatt zur Laufzeit innerhalb eine Composite-Routine wie folgt erstellt hinzuzufügen:
def update(self, tp, msg, stt):
"""It updates composite objects
"""
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
Innenhaupt:
import lib.composite
c = Composite()
for i in range(0,10):
c.update(str(i), msg, stt)
und der Verbund:
class Composite(Component):
def __init__(self, *args, **kw):
super(Composite, self).__init__()
self.children = []
def append_child(self, child):
self.children.append(child)
def update(self, tp, msg, stt):
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
def status(self):
for child in self.children:
ret = child.status()
if type(child) == Leaf:
p_out("Leaf: %s has value %s" % (child, ret))
class Component(object):
def __init__(self, *args, **kw):
if type(self) == Component:
raise NotImplementedError("Component couldn't be "
"instantiated directly")
def status(self, *args, **kw):
raise NotImplementedError("Status method "
"must be implemented")
class Leaf(Component):
def __init__(self):
super(Leaf, self).__init__()
self._dict = {}
def setDict(self, type, key, value)
self._dict = { type : { key : value } }
def status(self):
return self._dict
Aber auf diese Weise fand ich immer, dass mein Composite nur ein Blatt ("d") hinzugefügt hat, selbst wenn Update mehrmals aufgerufen wurde.
Wie kann ich eine solche Routine so programmieren, dass Composite zur Laufzeit gefüllt werden kann?
Können Sie ein vollständiges Beispiel eines Programms geben, das dieses Problem demonstriert? –
vielleicht self.append_child immer an die letzte erinnern? – sunqiang
@Greg: Code hinzugefügt (hoffe hilfreich) – DrFalk3n