zoukankan      html  css  js  c++  java
  • python学习之闭包

    闭包:是由函数及其相关应用环境组合而成的实体(函数+引用环境)

    在嵌套函数中中,如果一个内部函数对外部函数(非全局作用域)中的变量进行引用,内部函数被认为是闭包

    闭包中不能修改外部环境的变量中的值

    def foo():
        m = 1
        def bar():
            m = 0
            print(m)
        print(m)
        bar()
        print(m)
    foo()
    
    1
    0
    1

    闭包经典错误

    def foo():  
        a = 1  
        def bar():  
            a = a + 1  
            return a  
        return bar  
    

      UnboundLocalError: local variable 'a' referenced before assignment    在赋值之前引用的局部变量'a'

    错误原因:python函数中如果出先内部作用域和外部作用域变量冲突,先在内部作用域找,找不见时向外找,而bar函数中对a进行重新赋值,但赋值时又使用内部作用域没有的值,故出现次错误,要想解决可以使用类似list此类容器

  • 相关阅读:
    DB2
    Data Queue
    QMQY
    CMD(SA400 Command)
    Software development process
    CSS display样式
    CSS行高line-height解释
    CS和CS3知识点
    HTML图片<img>标签空白解决方法
    CS清除浮动
  • 原文地址:https://www.cnblogs.com/Json28/p/10293139.html
Copyright © 2011-2022 走看看