zoukankan      html  css  js  c++  java
  • Python中的闭包和nonlocal关键字

    闭包概念

    自由变量:嵌套函数中,未在本地作用域中定义的变量,但在外层函数中定义了

    内层函数引用了外层函数中定义的自由变量,就形成闭包。函数调用后,闭包的变量值不会被丢弃。

    def outer():
        lst = [0]
    
        def inner():
            lst[0] += 1
            return lst[0]
        return inner
    
    foo = outer()
    print(foo(), foo())     ## 由于使用了闭包,所以闭包的变量lst在函数调用完成后,其值不会被丢弃。
    c = 10                  ## 这里定义的c是全局变量,和函数内的变量无关,所以函数中的变量lst值不变
    print(foo())

    运行结果

    1 2
    3

    内层函数如果本地不存在变量,会逐级向上层找(不能是全局作用域)

    def add():
        lst =[0]
    
        def add2():
            lst1=[]
            lst1.append(lst[0]  + 1)
    
            def inner():
                lst[0]+=1
                return lst
    
            return inner
    
        return add2()
    
    
    foo = add()
    
    print(foo())
    print(foo())
    print(foo())

    运行结果

    [1]
    [2]
    [3]

    这是Python2版本中的闭包,Python3中引入了nonlocal关键字

    nonlocal关键字

    使用nonlocal关键字将变量标记为非本地作用域,而是在上级中的某一级局部作用域中定义,但是不能是全局作用域

    使用nonlocal解决上面代码中的问题

    def outer():
        x = 10
        def inner():
            nonlocal x
            x += 1
            return x
        return inner
    
    foo=outer()
    print(foo(),foo())

    运行结果

    11 12

    错误的使用nonlocal:在全局作用域中使用

    x = 20
    def outer():
        nonlocal x       ## nonlocal关键字定义的变量,不能提升到全局作用域
        x = 10
        def inner():
            nonlocal x
            x += 1
            return x
        return inner
    
    foo = outer()
    print(foo(),foo())

    运行结果

        nonlocal x
        ^
    SyntaxError: no binding for nonlocal 'x' found
  • 相关阅读:
    关键字: simpledateformat24小时 格式串
    浅谈DB2在线分析处理函数
    Java中的final关键字
    TestNG注解使用技巧
    java之静态方法,静态变量
    CssSelector之selenium元素定位
    收藏,常用正则表达式
    正则表达式小结
    [转]java中文乱码的解决
    多叉树结构:JSON数据解析(一)
  • 原文地址:https://www.cnblogs.com/zh-dream/p/13859078.html
Copyright © 2011-2022 走看看