• 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

  • 相关阅读:
    整除理论
    洛谷P1440 求m区间内的最小值
    洛谷 P1865 A % B Problem
    CF776B Sherlock and his girlfriend
    POJ2262 Goldbach's Conjecture
    BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(筛法思想)
    质数合数相关
    CPU缓存会分为一级缓存L1、L2、L3
    mysql+redis
    IntelliJ IDEA下的使用git
  • 原文地址:https://www.cnblogs.com/xxswkl/p/12031721.html
Copyright © 2020-2023  润新知