Python nonlocal statement

前端 未结 9 1220
我在风中等你
我在风中等你 2020-11-22 03:52

What does the Python nonlocal statement do (in Python 3.0 and later)?

There\'s no documentation on the official Python website and help(\"nonloca

9条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:18

    Compare this, without using 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
    

    To this, using nonlocal, where inner()'s x is now also outer()'s 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
    

    If we were to use global, it would bind x to the properly "global" value:

    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
    

提交回复
热议问题