global 和 nonlocal关键字

来源:互联网 发布:幼儿网络教育 编辑:程序博客网 时间:2024/06/07 05:11

当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了。
以下实例修改全局变量 num:

#!/usr/bin/python3num = 1def fun1():    global num  # 需要使用 global 关键字声明    print(num)     num = 123    print(num)fun1()

以上实例输出结果:

1123

如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字了,如下实例:

#!/usr/bin/python3def outer():    num = 10    def inner():        nonlocal num   # nonlocal关键字声明        num = 100        print(num)    inner()    print(num)outer()

以上实例输出结果:

100100

另外有一种特殊情况,假设下面这段代码被运行:

#!/usr/bin/python3a = 10def test():    a = a + 1    print(a)test()

以上程序执行,报错信息如下:

Traceback (most recent call last):  File "test.py", line 7, in <module>    test()  File "test.py", line 5, in test    a = a + 1UnboundLocalError: local variable 'a' referenced before assignment

错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。