为了账号安全,请及时绑定邮箱和手机立即绑定

Python非本地语句

Python非本地语句

慕的地6264312 2019-07-06 13:26:05
Python非本地语句Python是什么nonlocal语句do(在Python3.0及更高版本中)?官方Python网站上没有文档help("nonlocal")也不起作用。
查看完整描述

3 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

比较这一点,而不使用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


查看完整回答
反对 回复 2019-07-06
?
LEATH

TA贡献1936条经验 获得超6个赞

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


查看完整回答
反对 回复 2019-07-06
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

谷歌搜索了“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,但是对于初学者来说,第一个版本似乎更明显。通过调用返回的函数正确地使用生成器是一个常见的混淆点。第一个版本显式地返回一个函数。


查看完整回答
反对 回复 2019-07-06
  • 3 回答
  • 0 关注
  • 518 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信