【问题标题】:How do Python nonlocal and global work together?Python 非本地和全局如何协同工作?
【发布时间】:2018-10-03 10:50:49
【问题描述】:

这是我的例子

x=0
def outer():
    x = 1
    def i1():
        nonlocal x
        x = 2
        print("inner1:", x)

    i1()
    print("outer:", x)

    def i2():
        nonlocal x
        x = 3
        print("inner2:", x)

    i2()
    print("outer:", x)

    def i3():
        global x
        print("inner3:", x)

    i3()
    print("outer:", x)

outer()
print("global:", x)

在我的 Jupyter 中输出

inner1: 2
outer: 2
inner2: 3
outer: 3
inner3: 0
outer: 3
global: 0

为什么 outer 的值为 0?

【问题讨论】:

  • "为什么 outer 的值为 0?" 根据您的输出,它的值为 3。
  • 如果你问的是 global x,那是因为你从来没有给它赋值 0 以外的值。

标签: python closures


【解决方案1】:

i3()中,当你声明global x时,它确实使用了最外层的x,但是你并没有改变它的值。

在这部分代码中:

i3()
print("outer:", x)

print 命令在i3() 方法之外,因此 使用了全局x。将使用本地xi3() 中的 global 命令意味着只有在 i3() 中使用的 x 将是全局的。一旦超出i3()x 的声明global 范围将结束。

因此,print("outer:", x) 打印 3,这是 outer() 方法的局部变量的值。最外层的x 始终保持为0。

【讨论】:

    【解决方案2】:

    我认为您的测试用例有错误。如果我将i3 更改为:

        def i3():
            global x
            x = "i3"
            print("inner3:", x)
    

    然后我得到

    global: i3
    

    最后,正如我所料。

    【讨论】:

    • 您正在将字符串分配给 x
    • 是的,因此很明显该分配来自i3。数字 3 已在其他地方使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    相关资源
    最近更新 更多