内部函数修改外部函数的局部变量

当用到函数嵌套的时候, 内部函数正常情况下也是无法修改外部函数的局部变量, 只能访问读取.

如果想修改怎么办?

使用关键字:nonlocal

a = 10


def outer():
    a = 20

    def inner():
        nonlocal a  # 把 a 绑定到外部函数的局部变量 a 上
        a = 30

    inner()

    print("outer 的局部变量a:" + str(a))  # 30 被内部函数 inner 修改了


outer()

print("全局变量a:" + str(a))

Copyright © 李振超 2018 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-02-25 07:12:09

results matching ""

    No results matching ""