一、装饰器实现一个函数计时器
代码示例:
import time
import random
import string
import functools
li = [random.choice(string.ascii_letters) for i in range(100)]
print(li)
def Timer(fun):
"""这是一个装饰器Timer"""
def wrapper(*args,**kwargs):
"""这是一个wrapper函数"""
start_time = time.time() #执行函数前的记时
res = fun(*args,**kwargs)
end_time = time.time() #执行函数后的记时
print('运行时间为: %.5f' %(end_time - start_time)) #打印执行函数所用的时间
return res
return wrapper
@Timer
def con_add():
s = ''
for i in li:
s += (i + ',')
print(s)
@Timer
def join_add():
print(','.join(li))
@Timer
def fun_list(n):
"""这是fun_list函数"""
return [i * 2 for i in range(n)]
@Timer
def fun_map(n):
return list(map(lambda x:x*2,range(n)))
con_add()
join_add()
print(fun_list(100))
print(fun_map(100))
执行效果:
二、多个装饰器
示例1:
def decorator_a(fun):
print('Get in decorator_a')
def inner_a(*args, **kwargs):
print('Get in inner_a')
res = fun(*args, **kwargs)
return res
return inner_a
def decorator_b(fun):
print('Get in decorator_b')
def inner_b(*args, **kwargs):
print('Get in inner_b')
res = fun(*args, **kwargs)
return res
return inner_b
@decorator_a
@decorator_b
def f(x):
print('Get in f')
return x * 2
f(2)
执行效果:
示例2:
import functools
import inspect
def is_admin(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
#inspect.getcallargs返回一个字典,key值是形参,value值
#是对应的实参{'name':'root'}
inspect_res = inspect.getcallargs(fun,*args,*kwargs)
print('inspect的返回值: %s' %inspect_res)
if inspect_res.get('name') == 'root':
res = fun(*args,**kwargs)
return res
else:
print('not root user!')
return wrapper
login_session = ['root', 'redhat', 'redhat']
def is_login(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
if args[0] in login_session:
res = fun(*args,**kwargs)
return res
else:
print('Error:%s未登录' %args[0])
return wrapper
@is_login
@is_admin
def add_student(name):
print('添加学生信息...')
add_student('root')
执行效果: