zoukankan      html  css  js  c++  java
  • 8 python-- 闭包函数和装饰器

    闭包函数定义

    #内部函数包含对外部作用域而非全局作用域的引用
    
    #提示:之前我们都是通过参数将外部的值传给函数,闭包提供了另外一种思路,包起来喽,包起呦,包起来哇
    
            def counter():
                n=0
                def incr():
                    nonlocal n
                    x=n
                    n+=1
                    return x
                return incr
    
            c=counter()
            print(c())
            print(c())
            print(c())
            print(c.__closure__[0].cell_contents) #查看闭包的元素

    应用场景

    #闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
    #应用领域:延迟计算(原来我们是传参,现在我们是包起来)
        from urllib.request import urlopen
    
        def index(url):
            def get():
                return urlopen(url).read()
            return get
    
        baidu=index('http://www.baidu.com')
        print(baidu().decode('utf-8'))
    View Code

    了解闭包函数

    '''
    闭包:
    1. 定义在内部函数
    2. 包含对外部作用域而非全局作用域的引用,
    该内部函数就成为闭包函数
    '''
    # def f1():
    #     x=1
    #     def f2():
    #         print(x)
    #
    #     return f2
    #
    # f=f1()
    # print(f)
    
    #闭包应用:惰性计算
    from urllib.request import urlopen
    #
    # res=urlopen('http://crm.oldboyedu.com').read()
    # print(res.decode('utf-8'))
    
    def index(url):
        def get():
            return urlopen(url).read()
        return get
    
    oldboy = index('http://crm.oldboyedu.com')
    # print(oldboy().decode('utf-8'))
    print(oldboy.__closure__[0].cell_contents)
    
    def f1():
        # x=1
        y=2
        def f2():
            print(x,y)
        return f2
    f=f1()
    print(f.__closure__[0].cell_contents)
    View Code

    装饰器是闭包函数的一种

    装饰器他人的器具,本身可以是任意可调用对象,被装饰者也可以是任意可调用对象。
    强调装饰器的原则:1 不修改被装饰对象的源代码 2 不修改被装饰对象的调用方式
    装饰器的目标:在遵循1和2的前提下,为被装饰对象添加上新功能

    了解装饰器

    '''
    装饰器:修饰别人的工具,修饰添加功能,工具指的是函数
    
    装饰器本身可以是任何可调用对象,被装饰的对象也可以是任意可调用对象
    
    
    为什么要用装饰器:
        开放封闭原则:对修改是封闭的,对扩展是开放的
        装饰器就是为了在不修改被装饰对象的源代码以及调用方式的前提下,为期添加新功能
    
    '''
    
    
    
    
    # import time
    #
    # def timmer(func):
    #     def wrapper(*args,**kwargs):
    #         start_time=time.time()
    #         res=func(*args,**kwargs)
    #         stop_time=time.time()
    #         print('run time is %s' %(stop_time-start_time))
    #     return wrapper
    #
    # @timmer
    # def index():
    #
    #     time.sleep(3)
    #     print('welcome to index')
    #
    # index()
    
    
    
    # import time
    #
    # def timmer(func):
    #     def wrapper():
    #         start_time=time.time()
    #         func() #index()
    #         stop_time=time.time()
    #         print('run time is %s' %(stop_time-start_time))
    #     return wrapper
    #
    #
    # @timmer #index=timmer(index)
    # def index():
    #     time.sleep(3)
    #     print('welcome to index')
    #
    #
    # # f=timmer(index)
    # # # print(f)
    # # f() #wrapper()---->index()
    #
    # # index=timmer(index) #index==wrapper
    #
    # index() #wrapper()----->
    
    
    
    #流程分析
    # import time
    # def timmer(func):
    #     def wrapper():
    #         start_time=time.time()
    #         func()
    #         stop_time=time.time()
    #         print('run time is %s' %(stop_time-start_time))
    #     return wrapper
    #
    # @timmer #index=timmer(index)
    # def index():
    #     time.sleep(3)
    #     print('welcome to index')
    #
    #
    # index() #wrapper()
    
    
    
    
    
    
    
    
    # import time
    # def timmer(func):
    #     def wrapper(*args,**kwargs):
    #         start_time=time.time()
    #         res=func(*args,**kwargs)
    #         stop_time=time.time()
    #         print('run time is %s' %(stop_time-start_time))
    #         return res
    #     return wrapper
    #
    # @timmer #index=timmer(index)
    # def index():
    #     time.sleep(3)
    #     print('welcome to index')
    #     return 1
    #
    # @timmer
    # def foo(name):
    #     time.sleep(1)
    #     print('from foo')
    #
    #
    # res=index() #wrapper()
    # print(res)
    #
    # res1=foo('egon')  #res1=wrapper('egon')
    # print(res1)
    #
    #
    
    # def auth(func):
    #     def wrapper(*args,**kwargs):
    #         name=input('>>: ')
    #         password=input('>>: ')
    #         if name == 'egon' and password == '123':
    #             print('33[45mlogin successful33[0m')
    #             res=func(*args,**kwargs)
    #             return res
    #         else:
    #             print('33[45mlogin err33[0m')
    #     return wrapper
    #
    #
    #
    # @auth
    # def index():
    #     print('welcome to index page')
    # @auth
    # def home(name):
    #     print('%s welcome to home page' %name)
    #
    # index()
    # home('egon')
    #
    
    
    # login_user={'user':None,'status':False}
    # def auth(func):
    #     def wrapper(*args,**kwargs):
    #         if login_user['user'] and login_user['status']:
    #             res=func(*args,**kwargs)
    #             return res
    #         else:
    #             name=input('>>: ')
    #             password=input('>>: ')
    #             if name == 'egon' and password == '123':
    #                 login_user['user']='egon'
    #                 login_user['status']=True
    #                 print('33[45mlogin successful33[0m')
    #                 res=func(*args,**kwargs)
    #                 return res
    #             else:
    #                 print('33[45mlogin err33[0m')
    #     return wrapper
    #
    # @auth
    # def index():
    #     print('welcome to index page')
    # @auth
    # def home(name):
    #     print('%s welcome to home page' %name)
    # index()
    # home('egon')
    View Code
  • 相关阅读:
    中国石油昆仑加油卡
    157 01 Android 零基础入门 03 Java常用工具类01 Java异常 01 异常介绍 02 异常内容简介
    156 01 Android 零基础入门 03 Java常用工具类01 Java异常 01 异常介绍 01 Java常用工具类简介
    155 01 Android 零基础入门 02 Java面向对象 07 Java多态 07 多态知识总结 01 多态总结
    154 01 Android 零基础入门 02 Java面向对象 07 Java多态 06 内部类 05 匿名内部类
    153 01 Android 零基础入门 02 Java面向对象 07 Java多态 06 内部类 04 方法内部类
    152 01 Android 零基础入门 02 Java面向对象 07 Java多态 06 内部类 03 静态内部类
    151 01 Android 零基础入门 02 Java面向对象 07 Java多态 06 内部类 02 成员内部类
    150 01 Android 零基础入门 02 Java面向对象 07 Java多态 06 内部类概述 01 内部类概述
    149 01 Android 零基础入门 02 Java面向对象 07 Java多态 05 接口(重点)07 接口的继承
  • 原文地址:https://www.cnblogs.com/the-way-to-bifk/p/7774097.html
Copyright © 2011-2022 走看看