首页 > 编程语言 > 详细

python global 和 nonlocal 的理解

时间:2019-01-19 17:11:50      阅读:256      评论:0      收藏:0      [点我收藏+]

参考:
https://www.cnblogs.com/summer-cool/p/3884595.html
https://blog.csdn.net/xCyansun/article/details/79672634

对于global来说:

如果存在全局变量a,和函数 f 而函数f内部不存在 " a = expressions ",函数内部可以使用全局变量a;
示例代码如下:
代码

a = 10
def test1():
    b = a + 1
    print(b)
test1()

运行结果:
11

如果函数f内部存在 “a = expressions”, 那么有避免报错有两种方式:1.该表达式出现在函数使用变量a; 2.使用 global来声明该变量;
代码

a = 10
def test2():
    a = 12
    print(a)
test2()

运行结果:
12
代码

a = 10
def test2():
    print(a)
     a = 12
test2()

运行结果:
UnboundLocalError: local variable ‘a‘ referenced before assignment
代码

a = 10
def test2():
    global a
    print(a)
    a = 12
test2()

运行结果:
12

对于nonlocal来说:

主要用于让函数内部定义的函数访问外层函数定义的变量。
代码:

def outer():
    num = 1
    def inner1():
        print("inner1: %d" % (num))
        def inner2():
            nonlocal num = 3
            print("inner2: %d" % (num))
        inner2()
    inner1()
    print("outer: %d" % (num))
outer()

运行结果:
inner1: 1
inner2: 3
outer: 3
nonlocal所声明的变量必须在当前函数的外层函数定义,如果外部函数仅仅使用global声明全局变量,这种方式会报错:
代码:

def outer():
    num = 1
    def inner1():
        print("inner1: %d" % (num))
        def inner2():
            nonlocal num
            num = 3
            print("inner2: %d" % (num))
        inner2()
    inner1()
    print("outer: %d" % (num))
outer()

运行结果:
SyntaxError: no binding for nonlocal ‘num‘ found

python global 和 nonlocal 的理解

原文:https://www.cnblogs.com/lif323/p/10292072.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!