版权声明:©;2004 Microsoft Corporation. All rights reserved. https://blog.csdn.net/qq_42036824/article/details/86567748
- 题目1:
创建装饰器, 要求如下:
- 创建add_log装饰器, 被装饰的函数打印日志信息;
- 日志格式为: [字符串时间] 函数名: xxx, 运行时间:xxx, 运行返回值结果:xxx
import time
import functools
def add_log(func):
@functools.wraps(func)
def wrapper(*args,**kwargs):
start_time = time.time()
res = func(*args,**kwargs)
end_time = time.time()
run_time = end_time - start_time
return res,run_time
return wrapper
@add_log
def add(x,y):
time.sleep(1)
return x+y
res,run_time = add(1,10)
print("[%s] 函数名:%s ,运行时间:%s ,运行返回值结果:%s"%(time.ctime(),add.__name__,run_time,res))
结果:
[Sun Jan 20 22:10:36 2019] 函数名:add ,运行时间:1.0010979175567627 ,运行返回值结果:11
老师的:
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 wrapper
@add_log
def add(x,y):
time.sleep(1)
return x+y
add(1,10)
结果:
[Sun Jan 20 22:13:33 2019] 函数名:add,运行时间:1.001095,运行返回值结果:11
- 题目2:
如果输入为root用户,则打印添加学生信息
否则,则打印:not root user
此题目为了介绍inspect.getcallargs的用法
import functools
import inspect
def is_root(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
#inspect.getcallargs返回值是字典,key值为:形参,value值为:形参对应实参
inspect_res = inspect.getcallargs(fun,*args,**kwargs)
print('inspect_res的返回值为:%s' %inspect_res)
if inspect_res.get('name') == 'root':
res = fun(*args,**kwargs)
return res
else:
print('not root user')
return wrapper
@is_root
def add_student(name): ##此处的name为inspect.getcallargs返回字典中的key值
print('添加学生信息...')
add_student(input())
测试1:
westos ##输入
inspect_res的返回值为:{'name': 'westos'}
not root user
测试2:
root
inspect_res的返回值为:{'name': 'root'}
添加学生信息...
- 题目3:
- 编写装饰器required_ints, 条件如下:
1). 确保函数接收到的每一个参数都是整数; # 如何判断变量的类型?
type(s), isinstance(s,str)
2). 如果参数不是整形数, 抛出异常raise TypeError(“参数必须为整形”)
import functools
def required_ints(f):
@functools.wraps(f)
def wrapper(*args,**kwargs):
for arg in args + tuple(kwargs.values()):
##如果接收的参数不是整形
if not isinstance(arg,int):
raise TypeError('参数必须为整形')
##注意此处的else对应的是for而不是if
else:
return f(*args,**kwargs)
return wrapper
@required_ints
def add(*args,**kwargs):
##kwargs.values()返回的是一个列表,要转换成元组才能相加
return sum(args + tuple(kwargs.values()))
print(add(1,2,3,65,67,5,a=1,b=2))
结果:
146
如果:
print(add(1,2,3,65,67,1.0,a=1,b=2))
TypeError: 参数必须为整形
- 题目4:
- 编写装饰器required_types,条件如下:
1).当装饰器为@required_types(int,float)确保函数接收到的每一个参数都是int或者float类型;
2).当装饰器为@required_types(list)确保函数接收到的每一个参数都是list类型
3).当装饰器为@required_types(str,int)确保函数接收到的每一个参数都是str或者int类型
4).如果参数不满足条件,打印TypeError:参数必须为xxxx类型
def required_types(*kinds):
def required_ints(fun):
def wrapper(*args,**kwargs):
for i in list(args)+list(kwargs.values()):
##kinds为required_types中传入的参数,为或者的关系
if not isinstance(i,kinds):
print('TypeError:参数必须为',kinds)
##如果类型错误,则返回一个空值,否则执行break后函数没有返回值,就会返回一个None
return ''
break
else:
res = fun(*args,**kwargs)
return res
return wrapper
return required_ints
@required_types(int,float) ##接收的参数为int或者float
def add(a,b):
return a + b
print(add(1,2.1))
结果:
3.1
##如果接收一个不是int或float的参数,此处给一个字符,则会报错
print(add('a',2.1))
结果:
TypeError:参数必须为 (<class 'int'>, <class 'float'>)
##其他结果可自行验证