This article analyzes the Python scope usage. Share to everyone for your reference, as follows:
Each programming language has a concept of the scope of variables, Python is no exception, the following is a Python scope code demo:
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)
The output of the program:
After local assignment:test spamafter nonlocal assignment:nonlocal spamafter Global assignment:nonlocal spamIn global S Cope:global spam
Note: The local assignment statement is a spam binding that cannot change scope_test. The nonlocal assignment statement alters the spam binding of the scope_test, and the global assignment statement changes the spam binding from the module level.
Among them, nonlocal is the new keyword for Python 3.
You can also see that the spam is not pre-bound before the global assignment statement.
Summary:
When you encounter a global variable accessed in a program and you want to modify the value of a global variable, you can use the: global keyword, which declares that the variable is globally variable in a function
The nonlocal keyword is used to use an outer (non-global) variable in a function or other scope.
The Global keyword is well understood, as is the case in other languages. Here is another example of a nonlocal:
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 ())
Operation Result:
123
Turn from: Small Talk blog http://www.tantengvip.com/2015/05/python-scope/
I hope this article is helpful for Python program design.