nonlocal

来源:互联网 发布:sybase恢复数据库 编辑:程序博客网 时间:2024/06/01 16:49


在 Python 中,内层函数对外层作用域中的变量仅有只读访问权限!

而 nonlocal 可以使我们自由地操作外层作用域中的变量!


# 1. 内层函数"可以使用"外层作用域中的变量
def outside():
    msg = 'outside'
    def inside():
        print(msg)
    inside()
    print(msg)

>>> outside()
outside
outside

# 2. 内层函数"无法修改"外层变量
def outside():
    msg = 'outside'
    def inside():
        # 无法操作外层变量,这里实际上新建了一个内层局部变量罢了~
        msg = 'inside'
        print(msg)
    inside()
    print(msg)

>>> outside()
inside
outside

# 3. 使用 nonlocal 修改外层变量
def outside():
    msg = 'outside!'
    def inside():
        nonlocal msg
        msg = 'inside!'
        print(msg)
    inside()
    print(msg)

>>> outside()
inside
inside