码迷,mamicode.com
首页 > 编程语言 > 详细

python闭包

时间:2019-06-21 22:35:07      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:sum   free   pytho   python   cal   了解   ==   全局变量   price   

闭包

  • # 第一版: 没有保证数据的安全
    # 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闭包

标签:sum   free   pytho   python   cal   了解   ==   全局变量   price   

原文地址:https://www.cnblogs.com/W-Y-C/p/11067010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!