zoukankan      html  css  js  c++  java
  • [TimLinux] Python nonlocal和global的作用

    1. 执行代码

    以下实例都是通过执行以下代码,需要把以下执行代码放在后面实例代码的后面。

    a = outer_func()
    print("call a()") a() a() a() b
    = outer_func()
    print("call b()") b() b() b()

    2. 未使用nonlocal

    def outer_func():
        count = 3
        def inner_func():
            count += 1
            print("count", count)
        return inner_func
    
    #output>>>
    #    count += 1
    #UnboundLocalError: local variable 'count' referenced before assignment

    3. 使用nonlocal

    def outer_func():
        count = 3
        def inner_func():
            nonlocal count
            count += 1
            print("count", count)
        return inner_func
    
    # output>>>
    # call a()
    # count 4
    # count 5
    # count 6
    
    # call b()
    # count 4
    # count 5
    # count 6

    4. 使用global (出错)

    def outer_func():
        count = 3
        def inner_func():
            global count
            count += 1
            print("count", count)
        return inner_func
    
    # output>>>
    #     count += 1
    # NameError: name 'count' is not defined

    5. 使用global (成功)

    count = 3
    def outer_func():
        def inner_func():
            global count
            count += 1
            print("count", count)
        return inner_func
    
    # output>>>
    # call a()
    # count 4
    # count 5
    # count 6
    
    # call b()
    # count 7
    # count 8
    # count 9
  • 相关阅读:
    命令执行顺序控制与管道
    js获取返回首页
    手机站点击商务通无轨迹解决方法
    js文字向上滚动代码
    文字隐藏多余的文字
    QQ弹窗代码
    百度推送代码
    js手机站跳转
    js 判断时间,满足执行框架
    js切换换class
  • 原文地址:https://www.cnblogs.com/timlinux/p/9193222.html
Copyright © 2011-2022 走看看