Python中的嵌套函数作用域
我有下面的函数,它遍历嵌套树并打印结果Python中的嵌套函数作用域,python,tree,Python,Tree,我有下面的函数,它遍历嵌套树并打印结果 def walk_tree(tree): def read_node(node): print node for n in node['subnodes']: read_node(n) read_node(tree) 如果我想返回一个txt,其中包含在树上行走时收集的数据,我认为以下方法可以奏效: def walk_tree(tree): txt = ''
def walk_tree(tree):
def read_node(node):
print node
for n in node['subnodes']:
read_node(n)
read_node(tree)
如果我想返回一个txt,其中包含在树上行走时收集的数据,我认为以下方法可以奏效:
def walk_tree(tree):
txt = ''
def read_node(node):
txt += node
for n in node['subnodes']:
read_node(n)
read_node(tree)
但是txt
似乎不在read\u节点的范围内。有什么建议吗?
谢谢您可以试试:
def walk_tree(tree):
txt = '' # (1)
def read_node(node, txt=txt):
txt += node # (2)
for n in node['subnodes']:
read_node(n, txt)
read_node(tree)
这会将txt的walk\u tree
s值绑定到read\u node
中的默认值,该值应该保持不变(如果我对Python理论的理解是正确的)。txt
可以在read\u node
中访问,我认为这只是+=
的一些问题,txt
不在read\u节点的本地范围内
>>> def a():
... x = ""
... def b():
... x += "X"
... b()
... print x
...
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in a
File "<stdin>", line 4, in b
UnboundLocalError: local variable 'x' referenced before assignment
>>>
>>>
>>> def a():
... x = []
... def b():
... x.append("X")
... b()
... print "".join(x)
...
>>> a()
X
>>定义a():
... x=“”
... def b():
... x+=“x”
... b()
... 打印x
...
>>>()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第5行,在
文件“”,第4行,在b中
UnboundLocalError:赋值前引用了局部变量“x”
>>>
>>>
>>>定义a():
... x=[]
... def b():
... x、 附加(“x”)
... b()
... 打印“”连接(x)
...
>>>()
X
您应该使用list和“”。join(…)
而不是str+=…
。在Python中,您不能重新绑定外部作用域的变量(在您的示例中是遍历树的变量)
因此,这将失败:
def a():
def b():
txt += "b" # !!!
print txt
txt = "mytext"
b()
a()
但这将起作用:
def a():
def b():
# removed assignment: txt += "b"
print txt
txt = "mytext"
b()
a()
因此,您可能希望避免重新绑定:
def a():
def b():
obj["key"] = "newtext"
obj = {"key" : "mytext"}
b()
a()
这不起作用,因为字符串在Python中是不可变的,所以txt+=node
将创建一个新字符串,而不是更改现有字符串。