猿问

Python非本地语句

Python非本地语句

Python是什么nonlocal语句do(在Python3.0及更高版本中)?

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


慕的地6264312
浏览 519回答 3
3回答

qq_遁去的一_1

比较这一点,而不使用nonlocal:x = 0def 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 = 0def 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 = 0def 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

LEATH

简而言之,它允许将值赋值到外部(但非全局)范围内的变量。看见佩普3104所有血淋淋的细节。

慕码人8056858

谷歌搜索了“python non-local”,佩普3104,它完全描述了语句背后的语法和推理。简而言之,它的工作方式与global语句,但它用于引用函数既不是全局变量也不是本地变量的变量。这里有一个简单的例子,说明你可以用它做些什么。计数器生成器可以重写以使用它,这样它看起来更像带有闭包的语言的习惯用法。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,但是对于初学者来说,第一个版本似乎更明显。通过调用返回的函数正确地使用生成器是一个常见的混淆点。第一个版本显式地返回一个函数。
随时随地看视频慕课网APP

相关分类

Python
我要回答