简体   繁体   中英

Python non-local variables

Isn't it supposed to return 'inner: nonlocal' and 'outer: local'?? Can someone explain what's happening, thanks.

>>>>def outer():
        x = 'local'
        def inner():
            nonlocal x
            x='nonlocal'
            print('inner:',x)
        inner()
        print('outer:',x)

>>>outer()
 inner: nonlocal
 outer: nonlocal

You are setting x to 'nonlocal' by calling inner() . Thus, x is set to 'nonlocal' no matter where you try to print it from within outer() . Put the print statement before the call to inner() and it will work.

See enter link description here link for information on non-local .

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

In short, it lets you assign values to a variable in an outer (but non-global) scope.

If you remove the keyword nonlocal and try your program, you will observe:

inner: nonlocal
outer: local

Program:

def outer():
    x = 'local'
    def inner():
        x='nonlocal'
        print('inner:', x)
    inner()
    print('outer:', x)


outer()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM