# 静态语言:编译过程中会检查,会发下问题
# 动态语言:只有在运行时才会发现问题
# 1 由于编译期间不做任何检查,直到运行期间我呢提才会暴露
# 2 函数使用者并不知道参数类型的时候,容易传错参数类型
# 函数注解:给函数的形参一个类型,并有指向的return值
# python3.5开始引入
# 可以用于第三方工具(如:pycharm)提示是否有return
# 3.6可以对变量进行注解,如:i:int = 3

# 业务应用
# 检查实参类型
# __annotations__是一个字典,其中包括返回值类型的声明。
# inspect模块:提供回去对象信息的函数,可以检查函数和类、类型检查
# signature(callable)函数,可以获取签名(函数签名包含了一个函数的信息,包括:函数名、参数类型、函数所在的类和名称空间及其他信息)

# inspect模块
# inspect.isfunction(add) 是否是函数
# inspect.ismethod(add) 是否是类的方法
# inspect.isgenerator(add) 是否是生成器对象
# inspect.isgeneratorfunction(add) 是否是生成器函数
# inspect.isclass(add) 是否是类
# inspect.ismodule(inspect) 是否是模块
# inspect.isbuiltin(print) 是否是内建对象
# inspect模块 - parameter对象
# 保存在元组中,只读 OrderedDict([('x', ), ('y', ), ('args', ), ('kwargs', )])
# name 参数名
# annotation 参数注解,可能没有定义
# default 参数缺省值,可能没有定义
# empty 特殊的类,用来标记default属性或者注释annotation属性的空值
# kind 实参如何绑定到形参
# POSITIONAL_ONLY 值必须是位置参数提供
# POSITIONAL_OR_KEYWORD 值可以作为关键字或者位置参数提供
# VAR_POSITIONAL 可变位置参数,对应*args
# KEYWORD_ONLY keyword_only参数,对应*或者*args之后出现的非可变关键字参数
# VAR_KEYWORD 可变关键字参数,对应**kwargs

网友评论