Python非本地语句

发布于 2021-02-02 23:18:43

Python nonlocal语句有什么作用(在Python 3.0及更高版本中)?

官方Python网站上没有文档,help("nonlocal")也无法使用。

关注者
0
被浏览
76
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    比较一下,不使用nonlocal

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

    对此,使用nonlocal,其中inner()x是现在还outer()x

    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: 2
    # global: 0
    

    如果要使用global,它将绑定x到正确的“全局”值:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看