gpt4 book ai didi

python装饰器和方法

转载 作者:太空狗 更新时间:2023-10-29 21:44:49 24 4
gpt4 key购买 nike

这里是新的。此外,我是 python 的(非常)新手,并试图理解以下行为。有人可以向我解释为什么这个例子中的两种方法有不同的输出吗?

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()**********result from decorator**********parentchild1 (child of parent)child2 (child of parent)**********result by hand**********parentchild1 (child of parent)grandchild (child of child1)child2 (child of parent)

那么为什么装饰调用永远不会下降到孙节点?我显然遗漏了一些关于语法的东西......

最佳答案

在装饰器中,您正在遍历节点的子节点并在它们上调用原始、非递归方法

method(child, *args, **kwargs)

所以你只会深入一层。尝试用

替换该行
map_children(method)(child, *args, **kwargs)

您将获得与手动递归版本相同的输出。

关于python装饰器和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/699526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com