python2.7闭包的局限

def foo():
    a = 1
    def bar():
        a += 1
        print a
        if a == 10:
            return
        bar()
    bar()
foo()

结果运行出错

Traceback (most recent call last):
  File "temp.py", line 10, in 
    foo()
  File "temp.py", line 9, in foo
    bar()
  File "temp.py", line 4, in bar
    a += 1
UnboundLocalError: local variable 'a' referenced before assignment

修改

def foo():
    a = [1]
    def bar():
        print a
        a[0] += 1
        if a[0] == 10:
            return
        bar()
    bar()
foo()

运行成功

解释

原因在于Python的数字,字符串是"不可变类型".列表是"可变类型",而闭包中引用并修改的外部变量需要是可以修改的自由变量。

你可能感兴趣的:(python2.7闭包的局限)