python 如何在循环中创建同一类的不同实例
我的问题是:
我想在一个组合类(Composite)里面,动态地添加一些叶子对象(Leaf),也就是在运行时创建这些对象。具体的代码结构大概是这样的:
def update(self, tp, msg, stt):
"""It updates composite objects
"""
d = Leaf()
d.setDict(tp, msg, stt)
self.append_child(d)
return self.status()
在主程序里面:
import lib.composite
c = Composite()
for i in range(0,10):
c.update(str(i), msg, stt)
而这个组合类的结构是:
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
但是我发现这样做的时候,无论我调用更新(update)多少次,我的组合里面总是只有一个叶子对象("d")被添加进来。
我该怎么写这样的代码,才能在运行时动态地填充组合呢?
2 个回答
1
append_child这个东西是干嘛的?我觉得它应该是把叶子节点存放在一个列表里。真的是这样吗?
更新一下:在主函数里,你不应该把self作为第一个参数传进去。我觉得这样会引发一个错误。
下面的代码看起来是可以正常工作的
class Component(object): def __init__(self, *args, **kw): pass def setDict(self, *args, **kw): pass class Leaf(Component): def __init__(self, *args, **kw): Component.__init__(self, *args, **kw) class Composite(Component): def __init__(self, *args, **kw): Component.__init__(self, *args, **kw) self.children = [] def update(self, tp, msg, stt): """It updates composite objects """ d = Leaf() d.setDict(tp, msg, stt) self.append_child(d) return 0 def append_child(self, child): self.children.append(child) def remove_child(self, child): self.children.remove(child) c =Composite() for i in range(0,10): c.update(str(i), "", 0) print len(c.children)
3
“但是通过这种方式,我发现我的组合对象总是只添加了一个叶子节点(‘d’),即使更新被调用了很多次。”
不,这段代码让组合对象有十个子节点。
>>> c.children
[<__main__.Leaf object at 0xb7da77ec>, <__main__.Leaf object at 0xb7da780c>,
<__main__.Leaf object at 0xb7da788c>, <__main__.Leaf object at 0xb7da78ac>,
<__main__.Leaf object at 0xb7da78cc>, <__main__.Leaf object at 0xb7da792c>,
<__main__.Leaf object at 0xb7da794c>, <__main__.Leaf object at 0xb7da798c>,
<__main__.Leaf object at 0xb7da79ac>, <__main__.Leaf object at 0xb7da79cc>]
所以你觉得它只有一个的想法很奇怪。