Python:nolocal 和 global

# nolocal 和 global的不同,nolocal改变的是上级作用域里的变量,global改变的是全局作用域里的变量

# global
name = 'xueyou'


def outer():
    name = 'dehua'

    def inner():
        global name  # 将全局作用域里的name值更改,也即xueyou变成fucheng
        name = 'fucheng'

    inner()
    print(name)  # 作用域里的name值未变


outer()  # dehua
print(name)  # fucheng

# nolocal
name = 'xueyou'


def outer():
    name = 'dehua'

    def inner():
        nonlocal name  # 将上级作用域里的name值更改,也即dehua变成fucheng
        name = 'fucheng'

    inner()
    print(name)  # fucheng


outer()  # fucheng
print(name)  # 全局作用域的变量未改,输出xueyou
上一篇:10.10 – 尝试安装openjdk-6-jre时,ca-certificates-java失败


下一篇:Failed to connect to 127.0.0.1 port 1080: Connection refused