global与nonlocal

# global
# 1,在局部作用域声明一个全局变量
def func():
    global name
    name = 'ww'
    print(name)

func()
print(name)
print(globals())

# 2,修改一个全局变量
count = 1
def func():
    global count
    count += 1

func()
print(count)


# nonlocal

# 1,不能操作全局变量,即不能引用也不能对其进行操作
count = 1
def func1():
    nonlocal count
    print(count)

func1()

# 2,局部作用域:内层函数对外层函数的局部变量进行修改
def wrapper():
    count = 1
    def inner():
        nonlocal count
        count -= 1
    print(count)
    inner()
    print(count)

wrapper()

 

posted @ 2020-08-19 11:01  LGQ天  阅读(76)  评论(0编辑  收藏  举报