zoukankan      html  css  js  c++  java
  • Python -- 闭包

    5.14 闭包

    什么是闭包?

    闭包是存在嵌套函数当中的,内层函数对外层函数非全局变量的引用,这样就会产生一个闭包,所引用的变量就是一个自由变量,这个自由变量不会随着函数的结束而消失,会一直保存在内存,最终目的保证数据的安全

    # 第一版: 没有保证数据的安全
    l1 = []  #全局变量
    def make_average(price):
        l1.append(price)
        total = sum(l1)
        return total/len(l1)
    print(make_average(100000))
    print(make_average(110000))
    print(make_average(120000))
    '''
    有很多代码....
    '''
    l1.append(666)
    print(make_average(90000))
    
    # 第二版:每次执行l1是空的。
    def make_average(price):
        l1 = []
        l1.append(price)
        total = sum(l1)
        return total/len(l1)
    print(make_average(100000))
    print(make_average(110000))
    print(make_average(120000))
    
    # 为了保证数据的安全,闭包
    def make_average():
        
        l = []
        def average(price):
            l.append(price)
            tolal = sum(l)
            return total/len(l)
        
    	return average
    avg = make_average()
    print(avg(100000))
    print(avg(110000))
    print(avg(120000))
    
    # 判断一个函数是不是闭包 == 闭包函数有没有自由变量
    print(ret.__code__.co_freevars)
    
    # 了解
    print(ret.__code__.co_varnames)  # 函数中的局部变量
    
    # 闭包的应用:
    1,保证数据的安全。
    2,装饰器的本质。
    
    # 例一:
    def wrapper():
        a = 1
        def inner():
            print(a)
        return inner
    ret = wrapper()
    
    # 例二:
    a = 2
    def wrapper():
        def inner():
            print(a)
        return inner
    ret = wrapper()
    
    # 例三:
    def wrapper(a,b):
        '''
        :param a: 2
        :param b: 3
        :return:
        '''
        name = 'alex'
        def inner():
            print(a)
            print(b)
            name = 'alex'
    
        return inner
    a = 2
    b = 3
    ret = wrapper(a, b)
    
  • 相关阅读:
    linux基础知识-12
    linux基础知识-11
    linux基础知识-10
    安装与迁移Solo博客系统
    linux基础知识-9
    linux基础知识-8
    linux基础知识-7
    linux基础知识-6
    linux基础知识-5
    通俗解释下分布式、高并发、多线程
  • 原文地址:https://www.cnblogs.com/Agoni-7/p/11079778.html
Copyright © 2011-2022 走看看