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
  • 相关阅读:
    EntityManager 实例化方法
    Java Jpa 规范
    Spring HandlerInterceptor
    Spring data jpa
    Spring Security @PreAuthorize 拦截无效
    Java ee el表达式
    脏读&幻读
    OR查询是否会使得索引失效?
    ThinkPHP中的parseDSN方法的坑记录一下
    js , map中的坑
  • 原文地址:https://www.cnblogs.com/timlinux/p/9193222.html
Copyright © 2011-2022 走看看