您的位置:首页 > 编程语言 > Python开发

Python装饰器练习,判断函数参数类型

2019-01-23 22:17 239 查看

题目要求:

编写装饰器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(*types):
def required_int(fun):
@functools.wraps(fun)
def wrapper(*args,**kwargs):
for i in args:
if not isinstance(i,types):
print('TypeError',types)
#break
else:
inspect_res = fun(*args,**kwargs)
return inspect_res
return wrapper
return required_int
@required_types(str,int)
def add(*args,**kwargs):
print(args)
print(add(1,2,3,4,4,4,5,56,66,6,6,66,6,65,5,1))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: