装饰器
装饰器用于动态地为函数扩展功能,同时不改变原本的函数定义
最简单的装饰器
import time
def decorator(fun):
def wrapper():
start=time.time()
fun()
runtime=time.time()-start
print(runtime)
return wrapper
@decorator
def do_something():
print('play games!')
do_something()
play games!
0.0004916191101074219
目标函数带参数的装饰器
import time
def decorator(func):
def wrapper(name):
start=time.time()
func(name)
runtime=time.time()-start
print(runtime)
return wrapper
@decorator
def fun(name):
print('play {} game'.format(name))
fun('video')
play video game
0.0004968643188476562
目标函数带有不固定参数的装饰器
import time
def decorator(func):
def wrapper(*args,**kwargs):
start=time.time()
func(*args,**kwargs)
runtime=time.time()-start
print(runtime)
return wrapper
@decorator
def fun1(name):
print('play {} game'.format(name))
@decorator
def fun2(user,name):
print('{} plays {} game'.format(user,name))
@decorator
def fun3(user, name, fre):
print('{} plays {} game {} times a day'.format(user,name,fre))
fun1('video')
play video game
0.0004992485046386719
fun2('bob','video')
bob plays video game
0.0004944801330566406
fun3('bob','video','3')
bob plays video game 3 times a day
0.0004956722259521484
装饰器带参数
让目标函数执行指定次数
import time
def decorator(max):
def decorator(func):
def wrapper(*args,**kwargs):
start=time.time()
for i in range(max):
func(*args,**kwargs)
runtime=time.time()-start
print(runtime)
return wrapper
return decorator
@decorator(3)
def fun(name):
print('play {} games'.format(name))
fun('video')
play video games
play video games
play video games
0.0004942417144775391