首页 > 编程语言 > 详细

Python 装饰器与反射

时间:2021-06-17 09:33:44      阅读:19      评论:0      收藏:0      [点我收藏+]
def validate_input(obj, **kwargs):
    hints = get_type_hints(obj)
    for para_name, para_type in hints.items():
        if para_name == "return":
            continue
        if not isinstance(kwargs[para_name], para_type):
            raise TypeError("参数:{}类型错误,应该是{}".format(para_name, para_type))
def type_check(decorator):
    @wraps(decorator)
    def wrapper_decorator(*args, **kwargs):
        func_args = getfullargspec(decorator)[0]
        kwargs.update(dict(zip(func_args, args)))

        validate_input(decorator, **kwargs)
        return decorator(**kwargs)

    return wrapper_decorator

 

@type_check
def add(a: int, b: int) -> int:
    return a + b


if __name__ == __main__:
    print(add(18, "sss"))
    # from typing import get_type_hints
    # 
    # print(add.__annotations__)
    # print(get_type_hints(add))

 

Python 装饰器与反射

原文:https://www.cnblogs.com/tracydzf/p/14891563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!