8

ここで新しい。また、私は(非常に)Pythonが初めてで、次の動作を理解しようとしています。この例の 2 つのメソッドの出力が異なる理由を説明してもらえますか?

def map_children(method):
    def wrapper(self,*args,**kwargs):
        res = method(self,*args,**kwargs)
        for child in self._children:
            method(child,*args,**kwargs)            
        return res
    return wrapper

class Node(object):

    def __init__(self,name,parent=None):
        self._namestring = name
        if parent:
            self._parent = parent

        self._children = []

    @map_children
    def decorated(self):
        if hasattr(self,'_parent'):
            print '%s (child of %s)'%(self._namestring,self._parent._namestring)
        else:
            print '%s'% self._namestring

    def undecorated(self):
        if hasattr(self,'_parent'):
            print '%s (child of %s)'%(self._namestring,self._parent._namestring)
        else:
            print '%s'% self._namestring

        for child in self._children:
            child.undecorated()


def runme():
    parent = Node('parent')

    child1 = Node('child1',parent)
    child2 = Node('child2',parent)
    grandchild = Node('grandchild',child1)
    child1._children.append(grandchild)
    parent._children.append(child1)
    parent._children.append(child2)

    print '**********result from decorator**********'
    parent.decorated()

    print '**********result by hand**********'
    parent.undecorated()

私のシステムの出力は次のとおりです。

In[]:testcase.runme()
*********デコレーターからの結果*********
親
child1 (親の子)
child2 (親の子)
*********手作業による結果*********
親
child1 (親の子)
孫 (child1 の子)
child2 (親の子)

では、装飾された呼び出しが孫ノードに下がらないのはなぜでしょうか? 私は明らかに構文について何かが欠けています...

4

1 に答える 1

7

デコレーターでは、ノードの子をループし、の非再帰を呼び出してmethodいます

method(child, *args, **kwargs)

そのため、1 レベルだけ深くなります。その行を次のように置き換えてみてください

map_children(method)(child, *args, **kwargs)

手動の再帰バージョンと同じ出力が得られます。

于 2009-03-31T00:15:02.113 に答える