装饰器

#装饰器:本质是函数,装饰其他函数。就是为其它函数添加附加功能。

#timer(): #装饰器函数
# 嵌套子函数(*args,**kwargs):
# test1()
# return 嵌套子函数名
#test1() #被装饰的函数


#原则:
#1.不能修改被装饰的函数的源代码
#2.不能修改被装饰的函数的调用方式
#实现装饰器的知识储备:
#1.函数即“变量”
#2.高阶函数
#3.嵌套函数
#高阶函数+嵌套函数=装饰器

# @ 符号就是装饰器的语法糖,把它放在被装饰的函数前面,这样就可以省略最后一步再次赋值的操作。
# 装饰器的用法: 直接: @装饰器函数名 相当于:被装饰的函数名 = 装饰器(被装饰的函数名)

import time

def timer(func): #定义一个装饰器,func名称任意,用于代表被装饰的函数
def deco(*args,**kwargs): #嵌套函数,符合装饰器特征。在这里添加各种装饰命令。括号里面的形参可以接收各种参数,具有扩展性
start_time = time.time()
func(*args,**kwargs) #相当于调用了被装饰的函数
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time)) #给test1添加的额外命令
return deco #返回函数内存地址,不能少。否则出现:object is not callable不可调用错误

@timer # 语法糖,@timer是一个装饰器,在被装饰的函数前面添加。相当于执行了:test1 = timer(test1)
def test1(): #被装饰的函数
time.sleep(1)
print("in the test1")

@timer # 语法糖,@timer是一个装饰器,在被装饰的函数前面添加。相当于执行了:test2 = timer(test2)
def test2(name,age): #被装饰的函数
print("test2:",name,age)

test1() #关键部分:调用被装饰的函数,之后装饰器会自动执行。装饰器执行过程中,除test1正常执行外,还将执行装饰器中的其它命令
test2("alex",22) #关键部分:调用被装饰的函数,之后装饰器会自动执行。
#########################################################
#如果不用语法糖,也可以这样写:
import time

def timer(func):
def wrapper(*args,**kwargs):
start_time = time.time()
func()
stop_time = time.time()
print("%s run time is: %s\n" %(func.__name__,stop_time-start_time))
return wrapper

def test1():
time.sleep(1)
print("In the test1")

def test2():
time.sleep(1)
print("In the test2")

test1 = timer(test1) #相当于@语法糖
test2 = timer(test2) #相当于@语法糖

test1() #关键部分,调用被装饰的test1函数
test2()

posted @ 2017-10-25 10:35  浆糊jun  阅读(183)  评论(0编辑  收藏  举报