简体   繁体   English

Python 非本地和全局如何协同工作?

[英]How do Python nonlocal and global work together?

This is my example这是我的例子

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)

Output in my Jupyter在我的 Jupyter 中输出

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

Why does outer have value 0?为什么外层的值为 0?

In i3() , when you declare global x , it indeed uses the outermost x , but you haven't changed its value.i3() ,当您声明global x ,它确实使用了最外面的x ,但您没有更改它的值。

In this part of the code:在这部分代码中:

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

The print command is outside the i3() method, hence the global x is NOT being used. print命令在i3()方法之外,因此没有使用全局x It is the local x which will be used.这是将使用的本地x The global command in i3() means that only the x used within i3() will be global. i3()global命令意味着只有在i3()使用的x才是全局的。 Once outside i3() , the declared global scope for x will end.一旦超出i3()x声明的global范围将结束。

Thus, print("outer:", x) prints 3, which is the outer() method's local variable's value.因此, print("outer:", x)打印 3,这是outer()方法的局部变量的值。 The outermost x remains 0 throughout.最外面的x始终保持为 0。

I think your test case has a bug.我认为你的测试用例有一个错误。 If I change i3 to:如果我将i3更改为:

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

then I get然后我得到

global: i3

at the end, as I would expect.最后,正如我所料。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM