1.装饰器的作用
装饰器:
把一个函数当作参数,返回一个替代版的函数
本质就是一个返回函数的函数
“在不改变原函数的基础上,给函数增加功能”
def desc(fun):
def add_info():
print('清明节快乐~')
fun()
return add_info
@desc
def login():
# print('清明节快乐~')
print('login...')
@desc
def logout():
print('logout...')
login()
logout()
对修改是封闭的,对扩展是开放的
import time
def f1():
# print(time.time())
print('This is a function...')
def f2():
print('This is a function...')
# print(time.time())
# f1()
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
print_current_time(f2)
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def f1():
print('This is a function...')
def f2():
print('This is a function...')
# f = decorator(f1)
f1()
import time
def decorator(func):
def wrapper(*args):
print(time.time())
func(*args)
return wrapper
@decorator
def f1(func_name):
print('This is a function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
f1('test')
f2('test1','test2')
import time
def decorator(func):
def warpper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return warpper
@decorator
def f1(func_name):
print('This is a function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
@decorator
def f3(func_name1,func_name2,**kwargs):
print('This is a function ' + func_name1)
print('This is a function ' + func_name2)
print(kwargs)
f1('test')
f2('test1','test2')
f3('test1','test2',a=1,b=2,c='westos')
import time
import functools
def add_log(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
start_time = time.time()
res = fun(*args,**kwargs)
end_time = time.time()
print('[%s] 函数名: %s, 运行时间: %6f,运行返回值结果: %d' %(time.ctime(),fun.__name__,end_time - start_time,res))
return res
return wrapper
@add_log
def add(x,y):
time.sleep(1)
return x + y
add(1,2)
2.多个装饰器使用
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)
3.装饰器练习
1)题目:
装饰器实现一个函数计时器
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"""
# @functools.wraps(fun)
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))
print(fun_list.__doc__)
print(fun_list.__name__)
print(time.ctime())
2)题目:
编写装饰器required_types, 条件如下:
(1). 当装饰器为@required_types(int,float)确保函数接收到的
每一个参数都是int或者float类型;
(2). 当装饰器为@required_types(list)确保函数接收到的每一>个参数都是list类型;
(3). 当装饰器为@required_types(str,int)确保函数接收到的每
一个参数都是str或者int类型;
(4). 如果参数不满足条件, 打印 TypeError:参数必须为xxxx类
型
import functools
def required_types(*kinds):
def required_int(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
for i in args:
if not isinstance(i, kinds):
# print('TypeError:参数必须为',kinds)
# break
raise TypeError('参数必须为%s,%s' % kinds)
else:
res = fun(*args, **kwargs)
return res
return wrapper
return required_int
@required_types(float, float)
def add(a, b):
return a + b
print(add(1.1, 2.0))