zoukankan      html  css  js  c++  java
  • 装饰器

    decrator

    装饰器:
    定义:本质是函数,(装饰其他函数)就是为其他函数添加功能
    原则:1、不能修改被装饰的函数的源代码
            2、不能修改被装饰的函数的调用方式

    实现装饰器的功能知识储备
    1、函数即变量

        把函数当成参数传递给另一个函数
    2、高阶函数(满足其一)
        a:把一个函数名当做实参传递给另外一个函数(在不修改被装饰函数的源代码的情况下为
           其他函数添加功能)
        b:返回值中包含函数名(不修改函数的调用方式)
    3、嵌套函数

        在函数中又有函数

    高阶函数+嵌套函数-》装饰器

    ########被装饰的函数无参数时###############
    import time
    def timmer(func):   #timer(test1)   func=test1
        def warpper(*args,**kwargs):
            start_time=time.time()
            func()  #run test1()
            stop_time=time.time()
            print("The func run time is %s"%(stop_time-start_time))
        return warpper
    @timmer  #等价于test1=timmer(test1)  =warpper      test1()=warpper()
    def test1():
        time.sleep(3)
        print("This is the test1")
    
    @timmer
    def test2():
        time.sleep(3)
        print("This is the test2")
    test1()
    test2()
    

      

    ###########被装饰的函数有参数时############
    import time
    def timmer(func):   #timer(test1)   func=test1
        def warpper(*arg,**kwargs):##适用于所有函数形式即有无参数
            start_time=time.time()
            func(*arg,**kwargs)  #run test1(name)
            stop_time=time.time()
            print("The func run time is %s"%(stop_time-start_time))
        # def warpper(arg1,age):#传递过来的参数
        #     start_time=time.time()
        #     func(arg1,age)  #run test1(name)
        #     stop_time=time.time()
        #     print("The func run time is %s"%(stop_time-start_time))
        return warpper
    @timmer  #等价于test1=timmer(test1)  =warpper      test1(name,age)=warpper(name,age)
    def test1(name,age):
        time.sleep(3)
        print("This is the test1:",name,age)
    View Code有参数的装饰器
  • 相关阅读:
    tomcat work 目录
    上传图片预览 支持IE8+,FF,Chrome ,保留原图片比例
    设计模式学习笔记-观察者模式
    jcarousellite 实现图片列表滚动
    linux一些常用命令
    http&https&证书&数字签名
    醉笑陪君三万场 不诉离伤
    笔记本光驱位安装固态硬盘及window系统一些过程记录
    linux 添加定时任务脚本
    设置 SSH 免密码登陆——仍提示输入密码
  • 原文地址:https://www.cnblogs.com/WhatTTEver/p/6680341.html
Copyright © 2011-2022 走看看