前言
静态语言:运行之前能确定数据类型的语言
动态语言:数据类型需要在运行时才确定
Python是一门动态语言 边运行 边解释
需求
Python弱化了数据类型的概念
只要编写代码人清楚变量的具体类型即可
不需要明确告诉计算机(其实计算机也是清楚的 可以进行一定的推断)
观察一个现象
Python中的类型声明并不等于做强制类型转换
可以不按照规定的数据类型使用(往往不会出现运行错误)
但为了程序的健壮性稳定性
我们需要进行人工的数据类型检查
实现
如何实现函数类型与返回值的强制性检查?
引入相关库 from typing import get_type_hints
通过get_type_hints函数获取函数的标签
通过函数修饰器 使得函数具备强制检查类型的功能
from typing import get_type_hints
from functools import wraps
from inspect import getfullargspec
# 定义函数参数类型的检查函数
def parameter_check(obj, **kwargs):
hints = get_type_hints(obj)
for label_name, label_type in hints.items():
# 返回类型不检查 跳过 只检查实际传入参数的类型是否正确
if label_name == "return":
continue
# 判断实际传入的参数是否与函数标签中的参数一致
if not isinstance(kwargs[label_name], label_type):
raise TypeError("参数:{} 类型错误 应该为:{}".format(label_name, label_type))
# 使用装饰器进行函数包裹
def wrapped_func(decorator):
@wraps(decorator)
def wrapped_decorator(*args, **kwargs):
func_args = getfullargspec(decorator)[0]
kwargs.update(dict(zip(func_args, args)))
parameter_check(decorator, **kwargs)
return decorator(**kwargs)
return wrapped_decorator
@wrapped_func
def add0(a: int, b: int) -> int:
return a + b
@wrapped_func
def add1(a: int, b: float = 520.1314) -> float:
return a + b
print(add0(1, 1))
print(add0("hello", "world"))
小结
在Python这门动态语言中
只有运行到出现错误的位置才会报错
运行到错误位置之前不会出现异常