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

题目要求:

 编写装饰器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))

猜你喜欢

转载自blog.csdn.net/weixin_43314056/article/details/86618575