zoukankan      html  css  js  c++  java
  • python global 和 nonlocal 的理解

    参考:
    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

  • 相关阅读:
    tomcat log
    关于 终端 ls 命令 不能区分文件和目录的问题
    画幅
    透视
    焦距和等效焦距
    滚动条插件mCustomScrollbar
    网页优化总结
    CSS3中translate、transform和translation的区别和联系
    Less的学习和使用
    Koala工具的使用说明
  • 原文地址:https://www.cnblogs.com/lif323/p/10292072.html
Copyright © 2011-2022 走看看