赞
踩
3分钟
类型注解
,使用注解之外的类型也是不报错
的def test(uid: int):
print(uid)
test("999")
类型不对
就直接报错实现报错
,似乎有强类型语言
那味了装饰器
yydsimport inspect def type_check(func): def wrapper(*args, **kwargs): sig = inspect.signature(func) bound_args = sig.bind(*args, **kwargs) bound_args.apply_defaults() for name, value in bound_args.arguments.items(): param = sig.parameters[name] expected = param.annotation default_value = param.default if default_value != inspect.Parameter.empty: print('有默认值 => {}实际值={}'.format(name, value)) else: print('无默认值 => {}'.format(name)) # 有注解的参数 if expected != inspect.Parameter.empty: # 无默认值的参数 if default_value == inspect.Parameter.empty: if not isinstance(value, expected): raise TypeError(f"参数'{name}'应该是{expected}而不是{type(value)}") # 有默认值的参数(值必须是注解类型或者等于默认值) if value != default_value and not isinstance(value, expected): raise TypeError(f"参数'{name}'应该是{expected}而不是{type(value)}") return func(*args, **kwargs) return wrapper
@type_check def demo(n: int, msg: str, state: int = None): print('正常结束\n') # 正常调用 demo(1, 'SUCCESS') # 正常调用 demo(2, 'SUCCESS', 200) # 引发异常(第3个参数只能是int类型) demo(3, 'FAILED', '哈哈') # 引发异常(第1个参数只能是int类型) demo('4', "FAILED", '嘻嘻')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。