Home  >  Article  >  Backend Development  >  Python nonlocal and global keyword parsing instructions

Python nonlocal and global keyword parsing instructions

高洛峰
高洛峰Original
2017-03-12 10:49:222290browse

nonlocal

First of all, it must be clear that the nonlocal keyword is defined inside the closure. Please look at the following code:

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

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

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

Result

# inner: 2
# outer: 1
# global: 0

Now, add the nonlocal keyword to the closure to declare:

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

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

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

Result

# inner: 2
# outer: 2
# global: 0

See the difference? This is a function with another function nested inside it. When nonlocal is used, it is declared that the variable is not only valid
within the nested function inner(), but is valid within the entire large function.

global

Still the same, let’s look at an example:

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

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

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

Result

# inner: 2
# outer: 1
# global: 2

global starts with variables in the entire environment Acts on variables of function class instead of on variables of function class.

The above is the detailed content of Python nonlocal and global keyword parsing instructions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn