函数的命名空间

level = 'L0'
n = 22


def func():
    level = 'L1'
    n = 33
    s =88
    print(locals())

    def outer():
        n = 44
        level = 'L2'
        print(locals(),n)

        def inner():
            level = 'L3'
            print(locals(),s) #此外打印的n是多少?

        inner()
    outer()

func()
输出:
{'n': 33, 'level': 'L1', 's': 88}
{'level': 'L2', 'n': 44, 's': 88} 44
{'level': 'L3', 's': 88} 88  #查看引用才有locals()

nonlocal

x = 0
def outer():
    x = 1
    def inner():
        # nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)
输出
inner: 2
outer: 1 # 不把nonlocal x 注释,  此处 outer x =2
global: 0
posted @ 2021-04-19 23:05  ty1539  阅读(45)  评论(0编辑  收藏  举报