为什么子函数不在Python中继承范围?

sup*_*tah 5 python scope

我不明白为什么以下不起作用:

def foo( x ):
    n = 1
    summe = 0
    def bar():
        n -= 1
    for i in range(0,10):
        y = x+i+n
        x += i
        summe += y
        print "{0} = {1} + {2} + {3}".format(y,x,i,n)
        bar()
    print "summe =", summe
    return summe
Run Code Online (Sandbox Code Playgroud)

为什么bar()不继承范围foo()?这是我需要忘记的C'ism吗?我有办法让这项工作成功吗?

Ale*_*tti 15

PEP 3104为该问题提供了解释和解决方案.问题是Python将对名称的任何赋值视为局部变量声明.

>>> n = 1
>>> def bar():
>>>     n = n + 1
>>> 
>>> bar()
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    bar()
  File "<pyshell#7>", line 2, in bar
    n = n + 1
UnboundLocalError: local variable 'n' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

如果您使用不带nonlocal关键字的Python版本,则有一些解决此问题的方法.一个丑陋的技巧是将变量包装在一个列表中:

>>> n=[1]
>>> def bar():
>>>     n[0] = n[0] + 1
>>> 
>>> bar()
>>> n
[2]
Run Code Online (Sandbox Code Playgroud)

虽然这个技巧有效,但通常最好重写代码以消除对非本地分配的需要.