Python非本地语句

Python nonlocal语句做了什么(在Python 3.0和更高版本中)?

Python官方网站上没有任何文档, help("nonlocal")也不起作用。

比较这一点,不使用nonlocal

 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 

为此,使用nonlocal ,其中inner()x现在也是outer()x

 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 

如果我们要使用global ,它会把x绑定到正确的“全局”值:

 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 

简而言之,它允许您将值分配给外部(但非全局)范围的variables。 所有血淋淋的细节见PEP 3104 。

谷歌search“python nonlocal”提出了build议, PEP 3104 ,充分描述语句背后的语法和推理。 简而言之,它的工作方式与global声明完全相同,只是它用于指代对函数既不是全局也不是局部的variables。

这是一个简单的例子,你可以用这个做什么。 计数器生成器可以被重写使用,使它看起来更像是闭包语言的成语。

 def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter 

显然,你可以把它写成一个生成器,例如:

 def counter_generator(): count = 0 while True: count += 1 yield count 

但是,虽然这是完全习惯Python,似乎初学者的第一个版本会更加明显。 正确使用生成器,通过调用返回的函数,是一个常见的混淆点。 第一个版本显式返回一个函数。

帮助('nonlocal') nonlocal声明


  nonlocal_stmt ::= "nonlocal" identifier ("," identifier)* 

nonlocal语句会使列出的标识符引用最近的封闭范围中的以前绑定的variables。 这很重要,因为绑定的默认行为是首先search本地名称空间。 该语句允许封装代码除了全局(模块)作用域之外还重新绑定局部作用域之外的variables。

nonlocal语句中列出的名称与在global语句中列出的名称不同,必须引用封闭范围中的预先存在的绑定(无法明确确定应创build新绑定的范围)。

nonlocal语句中列出的名称不能与本地作用域中的预先存在的绑定相冲突。

也可以看看:

PEP 3104 – 在外部范围访问名称
nonlocal声明的规范。

相关帮助主题:global,NAMESPACES

来源: Python语言参考

@ooboo:

它采用与源代码中的参考点“最接近”的那个。 这就是所谓的“词法范围”,是现在40多年的标准。

Python的类成员确实在一个名为__dict__的字典中,并且永远不会通过词法范围来实现。

如果你不指定nonlocal但是x = 7 ,它将会创build一个新的局部variables“x”。 如果你指定nonlocal ,它会find“最接近的”“x”并分配给它。 如果你指定nonlocal并且没有“x”,它会给你一个错误信息。

global关键词总是让我觉得很奇怪,因为除了最外面的那个,它会高兴地忽略所有其他的“x”。 奇怪的。

我个人对“非本地”声明的理解(对于Python和编程一般来说,我不太了解),“非本地”是一种在迭代函数中使用全局function而不是代码本体。 function之间的全局声明,如果你愿意的话。

 a = 0 #1. global variable with respect to every function in program def f(): a = 0 #2. nonlocal with respect to function g def g(): nonlocal a a=a+1 print("The value of 'a' using nonlocal is ", a) def h(): global a #3. using global variable a=a+5 print("The value of a using global is ", a) def i(): a = 0 #4. variable separated from all others print("The value of 'a' inside a function is ", a) g() h() i() print("The value of 'a' global before any function", a) f() print("The value of 'a' global after using function f ", a)