Python nonlocal 关键字

实例

在函数内部创建一个函数,该函数使用变量 x 作为非局部变量:

  1. def myfunc1():
  2. x = "Bill"
  3. def myfunc2():
  4. nonlocal x
  5. x = "hello"
  6. myfunc2()
  7. return x
  8.  
  9. print(myfunc1())

定义和用法

nonlocal 关键字用于在嵌套函数内部使用变量,其中变量不应属于内部函数。

请使用关键字 nonlocal 声明变量不是本地变量。

更多实例

实例

与上例相同,但不使用 nonlocal 关键字:

  1. def myfunc1():
  2. x = "Bill"
  3. def myfunc2():
  4. x = "hello"
  5. myfunc2()
  6. return x
  7.  
  8. print(myfunc1())

相关页面

关键字 global 用于创建全局变量。