学习整理--python装饰器

使用场景:

       思考这样一个问题:对于生产系统,如何在修改最小,实现对原有模块添加新的功能呢?!通过装饰器,即可完成这一目标。

  装饰器有两个标准:

    1、不修改原有代码及原有调用方式;

    2、可以增加新的功能;

 

  例如,我们有一个方法func1,在这个方法中,打印两条信息并sleep 1秒钟。

def func1():
print("this is in the func1 methord")
time.sleep(1)
print("exec the func1 finished")

'''调用方法'''
if __name__ == "__main__":
  func1()

  现在我想不修改func1()方法及其调用方式的前提下,增加一个打印当前时间的功能,如何实现呢?

import time

def timmer(func):#定义装饰器timmer
def decotator(*args,**kwargs):#定义高阶函数
print("this is in the decorator,and current time is %s",args,kwargs)#添加的方法
func(*args,**kwargs)#执行传递变量的方法
return decotator#另其返回高阶函数地址

@timmer#指明装饰器为timmer,等价于func1=timmer(func1)
def func1():
print("this is in the func1 methord")
time.sleep(1)
print("exec the func1 finished")

@timmer
def func2(name):
print("this is in the func2 methord,and the name is :%s" %name)
time.sleep(1)
print("exec the func2 finished")



#调用func1方法
func1()
posted @ 2018-01-26 15:51  深海000111  阅读(94)  评论(0编辑  收藏  举报