Python中的嵌套函数作用域

时间:2010-03-02 13:11:50

标签: 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 read_node(node):
        txt += node
        for n in node['subnodes']:
            read_node(n)
    read_node(tree)

txt似乎不在read_node的范围内。有什么建议吗? 感谢

3 个答案:

答案 0 :(得分: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

无论如何,您应该使用列表和"".join(...)代替str += ...

答案 1 :(得分:5)

在Python中,您不能重新绑定外部作用域的变量(在您的示例中为walk_tree)。

所以这会失败:

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()

答案 2 :(得分:0)

你可以尝试:

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)

这会将walk_tree的txt值绑定到read_node中的默认值,该值应该保持不变(如果我对Python理论的掌握是正确的话)。