Python nonlocal and global keyword parsing instructions

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

nonlocal

First of all, it must be clear that the nonlocal keyword isdefinedinside 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 afunctionwith another function nested inside it. When nonlocal is used, it is declared that thevariableis 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!