zoukankan      html  css  js  c++  java
  • global和nonlocal的用法

    1 nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量.写在内部嵌套函数里面,它实质上是将该变量定义成了全局变量,它等价于用两个global来定义该变量.只不过用两个global来实现太繁琐.只用一个global的话无法在这儿(嵌套函数中)实现.

    def make_counter():
        global count
        count = 0
        def counter():
            # nonlocal count
            global count
            count += 1
            return count
        return counter
    mc = make_counter()
    print(mc())
    print(mc())
    print(mc())
    # 1
    # 2
    # 3
    View Code

    2 利用global可将函数的局部变量变为全局变量

    # 全局变量在函数内部可以任意调用
    hehe=6
    def f():
        print(hehe)
    f()
    print(hehe)
    # 6
    # 6
    
    # 注意这里在函数先输出hehe变量时,即先使用了它,后定义它是2,所以程序认为它是局部变量,会报先使用后定义的错误
    hehe=6
    def f():
        print(hehe)
        hehe=2
    f()
    print(hehe)
    # UnboundLocalError: local variable 'hehe' referenced before assignment
    
    # 这个是先定义后使用,函数内的hehe同样是局部变量
    hehe=6
    def f():
        hehe=2
        print(hehe)
    f()
    print(hehe)
    # 2
    # 6
    
    hehe=6
    def f():
        global hehe
        print(hehe)
        hehe=3
    f()
    print(hehe)
    # 6
    # 3
    参考: https://www.cnblogs.com/summer-cool/p/3884595.html
    View Code

    https://www.cnblogs.com/yuzhanhong/p/9183161.html

    https://www.liaoxuefeng.com/wiki/1016959663602400/1017434209254976#0

    https://www.cnblogs.com/tallme/p/11300822.html

  • 相关阅读:
    关于pipe管道的读写端关闭问题
    线性表的链式存储——C语言实现
    关于无法解析的外部符号 _main
    Tomcat域名与服务器多对多配置
    JavaScript基础
    Vue.js入门
    SpringBoot注解大全,收藏一波!!!
    数据库连接错误
    SpringBoot入门
    MyBatis插入并返回id技巧
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12031721.html
Copyright © 2011-2022 走看看