SoFunction
Updated on 2024-12-14

Explanation of the usage of python global and nonlocal.

这篇文章主要介绍了python global和nonlocal用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

◆globalrespond in singingnonlocalbePythonTwo important variable scoping keywords in the

Used in global variables, application scenarios:
When a variable is defined outside a function, if you want to change the value of the global variable inside the function, you need to redefine the variable inside the currently referenced function and modify it with the keyword global.

Example:

a=1
def b():
  a+=1
  print(a)
b()

When I finish writing this code with ide, it reports a red line error before it runs, and generates an error after it runs, which reads: UnboundLocalError: local variable 'a' referenced before assignment.

Solution:Redeclare the variable in the function with modifier globalModify.

#!/usr/bin/env python 
# encoding: utf-8 
a=1
def b():
  global a
  a+=1
  print(a)
b()

Non-global variables, application scenarios:

Use the function's variables inside the function's function. The expression may be a bit confusing, just look at the code

#!/usr/bin/env python 
# encoding: utf-8
def b():
  num2=1
  def c():
   nonlocal num2# To modify non-global variables
   num2+=2
   print(num2)
  return c
b()()

3. Integrated application

#!/usr/bin/env python 
# encoding: utf-8 
gcount = 0
 
def global_test():
  global gcount
  s=0
  def g():
    nonlocal s
    s+=2
    print(s)
  return g
  gcount+=1
  print (gcount)
global_test()()

This is the whole content of this article.