设为首页 加入收藏

TOP

Python nonlocal 与 global 关键字解析
2017-10-09 17:36:04 】 浏览:878
Tags:Python nonlocal global 关键字 解析

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

看到区别了么?这是一个函数里面再嵌套了一个函数。当使用 nonlocal 时,就声明了该变量不只在嵌套函数inner()里面
才有效, 而是在整个大函数里面都有效。

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

global 是对整个环境下的变量起作用,而不是对函数类的变量起作用。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于wxpython多线程研究包括(impo.. 下一篇python3.5 + PyQt5 +Eric6 实现的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目