好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python中关键字nonlocal和global的声明与解析介绍

这篇文章Python中关键字nonlocal和global的声明与解析介绍的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。

a = 10 
 
def foo(): 
 a = 100 
>>> a 
10 
>>> def foo(): 
...  global a 
...  a = 100 
... 
>>> a 
10 
>>> foo() 
>>> a 
100 
def countdown(start): 
 n = start 
 def decrement(): 
  n -= 1 
def countdown(start): 
 n = start 
 def decrement(): 
  nonlocal n 
  n -= 1 
x = 0
def outer():
 x = 1
 def inner():
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x) 
# inner: 2
# outer: 1
# global: 0 
x = 0
def outer():
 x = 1
 def inner():
  nonlocal x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x) 
# inner: 2
# outer: 2
# global: 0 
x = 0
def outer():
 x = 1
 def inner():
  global x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x) 
# inner: 2
# outer: 1
# global: 2 

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

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

查看更多关于Python中关键字nonlocal和global的声明与解析介绍的详细内容...

  阅读:35次