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关键字进行声明:

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 = 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
登录后复制

以上就是Python nonlocal与global关键字解析说明的详细内容,更多请关注Work网其它相关文章!

09-11 04:12