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的声明与解析介绍的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did85669