递归闭包中的范围错误 [英] scoping error in recursive closure

查看:195
本文介绍了递归闭包中的范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样工作:

def function1():                                                                                                             
       a = 10                                                                                                                    
       def function2():
          print a
       function2()

/ p>

but this does not:

def function1():
    a = 10
    def function2():
        print a
        a -= 1
        if a>0:
           function2()
    function2()

$ b b

我得到这个错误:

I get this error:

UnboundLocalError: local variable 'a' referenced before assignment


推荐答案

错误似乎不是非常描述根问题。 Mike解释了这些消息,但这不能解释根本原因。

The error doesn't seem to be very descriptive of the root problem. Mike explains the messages but that does not explain the root cause.

实际的问题是,在python你不能分配给关闭的过度变量。所以在function2'a'是只读的。当你分配给它,你创建一个新的变量,如Mike指出的,你在写之前读。

The actual problem is that in python you cannot assign to closed over variables. So in function2 'a' is read only. When you assign to it you create a new variable which, as Mike points out, you read before you write.

如果你想分配给外部变量你必须欺骗的内部范围如下:

If you want to assign to the to the outer variable from the inner scope you have to cheat like so:

def function1():
    al = [10]
    def function2():
        print al[0]
        al[0] -= 1
        if al[0]>0:
           function2()
    function2()

所以al是不可变的,但它的内容不是,你可以改变它们,新变量。

So al is immutable but its contents are not and you can change them without creating a new variable.

这篇关于递归闭包中的范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆