Python中的嵌套函数作用域

pis*_*hio 2 python tree

我有以下函数,它遍历嵌套树并打印结果

def walk_tree(tree):   
    def read_node(node):
        print node
        for n in node['subnodes']:
            read_node(n)
    read_node(tree)
Run Code Online (Sandbox Code Playgroud)

如果我想返回一个带有从树上行走收集的数据的txt,可以认为以下内容有效:

def walk_tree(tree):
    txt = ''  
    def read_node(node):
        txt += node
        for n in node['subnodes']:
            read_node(n)
    read_node(tree)
Run Code Online (Sandbox Code Playgroud)

txt似乎没有在read_node范围内.有什么建议吗?谢谢

Mes*_*ssa 6

txt是可访问的read_node,我认为这只是一些问题+=而且txt不在本地范围内read_node.

>>> 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
Run Code Online (Sandbox Code Playgroud)

你应该使用list而"".join(...)不是str += ...反正.


And*_*Dog 5

在Python中,您无法重新绑定外部作用域的变量(walk_tree在您的示例中).

所以这会失败:

def a():
    def b():
        txt += "b" # !!!

        print txt

    txt = "mytext"
    b()

a()
Run Code Online (Sandbox Code Playgroud)

但这会奏效:

def a():
    def b():
        # removed assignment: txt += "b"

        print txt

    txt = "mytext"
    b()

a()
Run Code Online (Sandbox Code Playgroud)

所以你可能想避免重新绑定:

def a():
    def b():
        obj["key"] = "newtext"

    obj = {"key" : "mytext"}
    b()

a()
Run Code Online (Sandbox Code Playgroud)