Python nonlocal 关键字
实例
在函数内部创建一个函数,该函数使用变量 x 作为非局部变量:
def myfunc1():
  x = "Bill"
  def myfunc2():
    nonlocal x
    x = "hello"
  myfunc2() 
  return x
print(myfunc1())
定义和用法
nonlocal 关键字用于在嵌套函数内部使用变量,其中变量不应属于内部函数。
请使用关键字 nonlocal 声明变量不是本地变量。
更多实例
实例
与上例相同,但不使用 nonlocal 关键字:
def myfunc1():
  x = "Bill"
  def myfunc2():
    x = "hello"
  myfunc2() 
  return x
print(myfunc1())
相关页面
关键字 global用于创建全局变量。
