当前位置:Gxlcms > Python > Pythonnonlocal与global关键字解析说明

Pythonnonlocal与global关键字解析说明

时间:2021-07-01 10:21:17 帮助过:68人阅读

nonlocal

首先,要明确 nonlocal 关键字是定义在闭包里面的。请看以下代码:

  1. x = 0
  2. def outer():
  3. x = 1
  4. def inner():
  5. x = 2
  6. print("inner:", x)
  7. inner()
  8. print("outer:", x)
  9. outer()
  10. print("global:", x)

结果

  1. # inner: 2
  2. # outer: 1
  3. # global: 0

现在,在闭包里面加入nonlocal关键字进行声明:

  1. x = 0
  2. def outer():
  3. x = 1
  4. def inner():
  5. nonlocal x
  6. x = 2
  7. print("inner:", x)
  8. inner()
  9. print("outer:", x)
  10. outer()
  11. print("global:", x)

结果

  1. # inner: 2
  2. # outer: 2
  3. # global: 0

看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面
才有效, 而是在整个大函数里面都有效。

global

还是一样,看一个例子:

  1. x = 0
  2. def outer():
  3. x = 1
  4. def inner():
  5. global x
  6. x = 2
  7. print("inner:", x)
  8. inner()
  9. print("outer:", x)
  10. outer()
  11. print("global:", x)

结果

  1. # inner: 2
  2. # outer: 1
  3. # global: 2

global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

以上就是Python nonlocal与global关键字解析说明的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行