zoukankan      html  css  js  c++  java
  • python闭包

    简单理解python中闭包的概念

    1、闭包的概念

    def test_add(num):
        '''
        在函数内部再定义⼀个函数,并且这个函数用到了外边函数的变量,
        那么将这个函数以及用到的一些变量称之为闭包
        '''
        def add_1(num2):
            return num+num2
        return add_1
    
    a1 = test_add(1)
    print(type(a1))
    print(a1(2))
    ''' 结果: <class 'function'> 3 '''

     第一次调用返回函数的对象,第二次调用才是调用函数内部的方法

    2、另一种闭包

    def counter(start):
        '''
        内部函数对外部函数作⽤域⾥变量的引⽤(⾮全局变量),则称内部函数为
        闭包
        '''
        count = [start]
        def incr():
            count[0] += 1
            return count[0]
        return incr
    
    c1 = counter(5)
    print(c1())
    print(c1())
    
    c2 = counter(10)
    print(c2())
    print(c2())
    
    '''
    结果:
    6
    7
    11
    12
    '''

     使用nonlocal访问外部函数的局部变量

    def counter(start=0):
        def incr():
            nonlocal start
            start += 1
            return start
        return incr
    
    c1 = counter(5)
    print(c1())
    print(c1())
    c2 = counter(50)
    print(c2())
    print(c2())
    print(c1())
    print(c1())
    
    print(c2())
    print(c2())

    '''
    结果:
    6
    7
    51
    52
    8
    9
    53
    54
    '''

    3、实际运用

    def line_conf(a, b):
        def line(x):
            return a*x + b
        return line
    line1 = line_conf(1, 1)
    line2 = line_conf(4, 5)
    print(line1(5))
    print(line2(5))

     4、闭包的作用

    (1)、闭包优化了变量,原来需要类对象完成的工作,可以通过闭包完成

    (2)、闭包引用了外部函数的局部变量,外部函数的局部变量无法及时释放,可以说是延长了局部变量的使用时间,避免了重复的创建,同时也消耗了内存

  • 相关阅读:
    TextFlow with JavaFX 2
    搞IT的技术人员为什么会如此苦逼
    Spring MVC3.0.5搭建全程
    JetNuke笔记 ( by quqi99 )
    What is the difference between application server and web server?
    Customize Netbeans Platform Splash Screen and About Dialog
    caffe-win10-cifar10
    Ubuntu14.04+caffe+CPU
    win10+caffe+GPU
    Majority Element(169) && Majority Element II(229)
  • 原文地址:https://www.cnblogs.com/wbw-test/p/10537083.html
Copyright © 2011-2022 走看看