python闭包

Posted w-y-c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python闭包相关的知识,希望对你有一定的参考价值。

闭包

  • # 第一版: 没有保证数据的安全
    # 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():
        l1 = []
        def average(price):
            l1.append(price)
            total = sum(l1)
            return total/len(l1)
        return average
    avg = make_average()
    # print(avg)
    print(avg(100000))
    print(avg(110000))
    print(avg(120000))
    # print(globals())
    #
    # def make_average():
    #
    #     count = 1
    #     def average():
    #         nonlocal count
    #         count += 1
    #         return count
    #     return average
    # avg = make_average()
    # # print(avg)
    # print(avg())
    # print(avg())
    # print(avg())
    # print(avg())
    # 例一:
    # 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)
    # 业哥 不是
    # 其他人 都说是
    # 判断一个函数是不是闭包 == 闭包函数有没有自由变量
    print(ret.__code__.co_freevars)
    # 了解
    print(ret.__code__.co_varnames)  # 函数中的局部变量
    # 闭包的应用:
    # 1,保证数据的安全。
    # 2,装饰器的本质。

以上是关于python闭包的主要内容,如果未能解决你的问题,请参考以下文章

python 闭包

python之闭包

python 闭包

Python闭包与装饰器

Python闭包函数

python的闭包