python的嵌套函数中局部作用域问题?
天蓬老师
天蓬老师 2017-04-17 17:17:39
0
2
224

python中赋值操作都会在当前作用域的locals()内部新绑定一个变量。因此如下的代码会报错:

def func1():
    x = 1
    print locals()
    def func2():
        print 'fun2:', locals()
        x += x
        print 'fun2:', locals()

    func2()
    print locals()

if __name__ == '__main__':
    func1()

报错就是

UnboundLocalError: local variable 'x' referenced before ssignment

但是为什么把x改成列表,然后以下面的方式:

def func1():
    x = [1, 2, 3]
    print locals()
    def func2():
        print 'fun2:', locals()
        x[0] += x[0]
        print 'fun2:', locals()

    func2()
    print locals()

if __name__ == '__main__':
    func1()

输出是:

{'x': [1, 2, 3]}
fun2: {'x': [1, 2, 3]}
fun2: {'x': [2, 2, 3]}
{'func3': <function func3 at 0x7f89da00ac08>, 'x': [2, 2, 3], 'func2': <function func2 at 0x7f89da00ab90>}

但是如果把x[0] += x[0]改成x = x[0]又报错了。
求解释啊。。。已经懵了---

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!