zoukankan      html  css  js  c++  java
  • 闭包中内函数如何修改外函数中局部变量的值

    1、

    >>> def a():
        x = 10
        def b():
            x = x + 8
            print(x)
        return b
    
    >>> a()
    <function a.<locals>.b at 0x000001B47F4D8040>
    >>> a()()
    Traceback (most recent call last):
      File "<pyshell#649>", line 1, in <module>
        a()()
      File "<pyshell#647>", line 4, in b
        x = x + 8
    UnboundLocalError: local variable 'x' referenced before assignment

    python认为在内部函数的x是局部变量的时候,外部函数的x就被屏蔽了起来,所以在执行 x = x + 8的时候找不到x的值,因此报错。

    >>> def a():
        x = [100]
        def b():
            x[0] = x[0] + 8
            print(x[0])
        return b
    
    >>> a()()
    108
    >>> c = a()
    >>> c()
    108
    >>> def a():
        x = 100
        def b():
            nonlocal x
            x = x + 8
            print(x)
        return b
    
    >>> a()
    <function a.<locals>.b at 0x000001DA3D2EA040>
    >>> a()()
    108
    >>> c = a()
    >>> c()
    108

     2、

    >>> def a():
        x = 10
        def b():
            nonlocal x
            x = x + 8
            print(x)
        return b
    
    >>> c = a()
    >>> c()
    18
    >>> c()
    26
    >>> c()
    34
    >>> for i in range(5):
        c()
    
        
    42
    50
    58
    66
    74

    闭包概念的引入是为了尽可能地避免使用全局变量,闭包允许将函数与其所操作的某些数据(环境)关联起来,这样外部函数就为内部函数构成了一个封闭的环境。

    参考:https://www.cnblogs.com/s-1314-521/p/9763376.html

  • 相关阅读:
    JS学习笔记ZT
    一条经典的汇总的sql
    sql 日期的转换
    微软.net安装失败时出现的问题
    sql 换行
    js 代码
    学习笔记
    decimal 的使用
    功能最完善,代码最简洁的选项卡代码(div+css)
    sql字母排序
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14488823.html
Copyright © 2011-2022 走看看