1

我的问题是:

我想将在运行时创建的 Composite 类 Leaf 对象添加到 Composite 例程中,如下所示:

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

但是通过这种方式,我总是发现我的复合材料只添加了一个叶子(“d”),即使 update 被调用了很多次。

我如何编写这样的例程以便能够在运行时填充复合材料?

4

2 回答 2

3

“但通过这种方式,我总是发现我的复合材料只添加了一个叶子(“d”),即使 update 被调用了很多次。”

不,该代码使 Composite 有十个孩子。

>>> 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>]

所以你为什么认为它只有一个很奇怪。

于 2009-07-09T11:27:46.587 回答
1

append_child 在做什么?我认为它应该将叶子存储在列表中。可以?

更新:您不应该将 self 作为主函数中的第一个参数传递。我认为它引发了一个例外。

请参阅下面似乎可以正常工作的代码

类组件(对象):
    def __init__(self, *args, **kw):
        经过

    def setDict(self, *args, **kw):
        经过

叶类(组件):
    def __init__(self, *args, **kw):
        Component.__init__(self, *args, **kw)

类复合(组件):
    def __init__(self, *args, **kw):
        Component.__init__(self, *args, **kw)
        self.children = []

    定义更新(自我,tp,味精,stt):
        """它更新复合对象
        """
        d = 叶()
        d.setDict(tp, msg, stt)
        self.append_child(d)

        返回 0

    def append_child(self, child):
        self.children.append(孩子)

    def remove_child(self, child):
        self.children.remove(孩子)

c =复合()
对于范围内的我(0,10):
    c.update(str(i), "", 0)
打印长度(c.children)
于 2009-07-09T09:58:12.413 回答