Home >Backend Development >Python Tutorial >Detailed explanation of Python scope usage example analysis

Detailed explanation of Python scope usage example analysis

高洛峰
高洛峰Original
2017-03-07 15:53:581209browse

The example of this article analyzes the usage of Python scope. Share it with everyone 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 code demonstration of Python scope:

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 spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Note: The local assignment statement cannot change the spam of scope_test Binding. The nonlocal assignment statement changes the spam binding of scope_test, and the global assignment statement changes the spam binding from the module level.

Among them, nonlocal is a new keyword added to Python 3.

You can also see that spam is not pre-bound before the global assignment statement.

Summary:

When you encounter the situation of accessing global variables in the program and want to modify the value of the global variable, you can use: global keyword, declare this variable in the function Is a global variable

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 is generally true for other languages. Here is another nonlocal example:

def make_counter():
  count = 0
  def counter():
    nonlocal count
    count += 1
    return count
  return counter
def make_counter_test():
 mc = make_counter()
 print(mc())
 print(mc())
 print(mc())

Running results:

1
2
3

More For more detailed explanations of Python scope usage examples and related articles, please pay attention to the PHP Chinese website!

Statement:
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