Python内部变量与外部变量

def outer():
    x = 'outer x'

    def inner():
        x = 'inner x'
        print(x)

    inner()
    print(x) # 这里的`x`与`x = 'outer x'`处在同一个Enclosing

outer()

运行结果:

inner x
outer x

使用nonlocal

def outer():
    x = 'outer x'

    def inner():
        nonlocal x
        x = 'inner x'
        print(x)

    inner()
    print(x)

outer()
posted @ 2017-06-19 20:26  2021年的顺遂平安君  阅读(50)  评论(0编辑  收藏  举报