Python 关键字之 nonlocal
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 关键字之 nonlocal相关的知识,希望对你有一定的参考价值。
在Python 3.x中增加了nonlocal关键字,关于变量的声明,引自官方文档:
Assignment of an object to a single target is recursively defined as follows.
If the target is an identifier (name):
-
If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.
-
Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal, respectively.
在当前作用域/代码块中,一个变量如果没有用关键字global或者nonlocal声明,则是局部变量,否则它是一个全局(global)变量 或者是外层作用域的非局部(nonlocal)变量。
python中引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量
注:如果只是引用全局变量或者外部变量,而不改变值的话,可以不加关键字,如果要改变值,则需要用关键字声明,否则会抛出error
example:
1 g_count = 5 2 3 def test1(): 4 x = g_count + 5 5 return x 6 7 print(test1()) # 输出 10
1 g_count = 5 2 3 def test1(): 4 #global g_count 不用global声明,会出现错误 5 g_count += 2 6 return g_count 7 8 print(test1())
UnboundLocalError: local variable ‘g_count‘ referenced before assignment,局部变量在定义之前被引用。
noncal关键字的使用
example:
1 def test3(): 2 counter = 0 3 def sub_test(): 4 nonlocal counter 5 counter += 2 6 return counter 7 return sub_test 8 9 10 f = test3() 11 print(f()) # ==>2 12 print(f()) # ==>4 13 print(f()) # ==>6
以上是关于Python 关键字之 nonlocal的主要内容,如果未能解决你的问题,请参考以下文章
python3raise,assert,nonlocal 关键字解读