python 设计模式之装饰器

设计模式:

1、装饰器:

     定义:本质是函数,(功能就是装饰其它函数)就是为其它函数添加附加功能

     原则:1、不能修改被装饰的函数的源代码

                2、不能修改被装饰的函数的调用方式

    简言之,python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能

import time

def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return warpper

@timmer
def test1():
time.sleep(3)
print("in the test1")

test1()

 

posted @ 2018-09-04 23:03  师弟-简单  阅读(453)  评论(0)    收藏  举报