Python: nonlocal 关键字

nonlocal 用来声明外层的局部变量。
global 用来声明全局变量。

nonlocal、global 关键字的用法:

a = 100
def outer():
    b = 10
    def inner():
        nonlocal b  # 声明外部函数的局部变量
        print(r"inner b:", b)
        b = 20
        global a  # 声明全局变量
        a = 1000
    inner()
    print(r"outer b:", b)
outer()
print("a :" ,a)

输出:
inner b: 10
outer b: 20
a : 1000

猜你喜欢

转载自blog.csdn.net/aixiangnan/article/details/88881255
今日推荐