This article mainly introduces the Python scope usage, and analyzes the concept and usage of the Python scope and related functions in detail based on the instance form, if you need it, you can refer to the example in this article to analyze the Python scope usage. We will share this with you for your reference. The details are as follows:
Every programming language has the concept of variable scope, and Python is no exception. The following is a demo of Python scope code:
def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam)scope_test()print("In global scope:", spam)
Program output result:
After local assignment: test spamAfter nonlocal assignment: nonlocal spamAfter global assignment: nonlocal spamIn global scope: global spam
Note: the local value assignment statement cannot change the spam binding of scope_test. The nonlocal assignment statement changes the spam binding of scope_test, and the global assignment statement changes the spam binding at the module level.
Nonlocal is a new keyword in Python 3.
You can also see that spam is not pre-bound before the global value assignment statement.
Summary:
You can use the global keyword to access the global variable in the program and modify the value of the global variable. declare this variable as a global variable in the function.
The nonlocal keyword is used to use outer (non-global) variables in functions or other scopes.
The global keyword is easy to understand, and the same applies to other languages. Here is another nonlocal example:
def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counterdef make_counter_test(): mc = make_counter() print(mc()) print(mc()) print(mc())
Running result:
123
For more details about Python scope usage instance analysis, please follow the PHP Chinese network!