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

Python nonlocal and global keyword parsing instructions

高洛峰
Release: 2017-03-12 10:49:22
Original
2346 people have browsed it

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)
Copy after login

Result

# inner: 2
# outer: 1
# global: 0
Copy after login

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)
Copy after login

Result

# inner: 2
# outer: 2
# global: 0
Copy after login

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)
Copy after login

Result

# inner: 2
# outer: 1
# global: 2
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template