global与nonlocal

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40612082/article/details/82978011

global是在函数内部声明变量为全局变量
nonlocal是声明该变量不是当前函数的本地变量

看如下例子:

x=300
def test1():
    x =200
    def test2():
        #global x
        nonlocal x
        print(x)
        x=100
        print(x)
    return test2

t1 = test1()
t1()

结果为:
200
100

x=300
def test1():
    x =200
    def test2():
        global x
        # nonlocal x
        print(x)
        x=100
        print(x)
    return test2

t1 = test1()
t1()

结果为:
300
100

猜你喜欢

转载自blog.csdn.net/weixin_40612082/article/details/82978011