This article brings you an introduction to the usage and difference between nonlocal and global in Python3 (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Keyword nonlocal
In Python 2.x, closures can only read the variables of the external function, but not overwrite it. In order to solve this problem, Python 3.x introduced the nonlocal keyword. Declaring variables with nonlocal within the closure allows the interpreter to find the variable name in the outer function.
Note: The keyword nonlocal: appears in python3.X, so it cannot be used directly in python2.x.
Keyword global
There are only two scopes in Python: Global scope and local scope. The global scope refers to the scope of the module where the current code is located, and the local scope refers to the scope of the current function or method. Code in the local scope can read variables in the external scope (including the global scope), but cannot change it. If you want to change it, you need to use the global keyword here
Example
The function of the keyword nonlocal is similar to the keyword global. The nonlocal keyword can be used to modify it in a nested function. Variables in nested scopes.
Look at two examples
Example 1
name = 'pythontab' def func() global name name = 'pythontab.com' func() print(name)
Result:
pythontab.com
Example 2
def func(): name = 'pythontab' def foo(): nonlocal name name = 'pythontab.com' foo() print(name) func()
Result:
pythontab.com
Note that in Example 2, the global keyword was not used to change the value of name.
Summary
The main differences are the following two points:
The above is the detailed content of Introduction to the usage and differences of nonlocal and global in Python3 (with examples). For more information, please follow other related articles on the PHP Chinese website!