装饰器

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有参数的装饰器

 

posted @ 2017-04-07 22:35  WhatTTEver  阅读(133)  评论(0编辑  收藏  举报