python语言变量没有类型,所以参数/列表中的元素都没有类型
优点:适合科学计算
缺点:没有类型就没有操作提示
解决方法便是类型标注
(1)语法:
1.变量:类型
2.def 函数名()->类型:
3.实例变量=数据 #type:类型
(2)作用:
增强代码可读性
类型检查
提示对应的操作
#对参数标注
def func(data:int):
#对返回值进行标注
def func() ->int
#对实例变量进行标注
class Myclass:
def __init__(self,data):
self.data=data #type:int
(3)复杂类型
List,Tuple,Dict,Union,Optional
Union[类型1,类型2,None]=Optional[类型1,类型2]
from typing import List,Tuple,Dict,Union,Optional
#容器
list=[] #type:List[str]
tuple=("",) #type:Tuple[str]
dict={} #type:Dict[str,float]
#多种类型
def func(a:Union[int,str]):
print(a)
#可选类型(可以不传递信息)
def func(a:Optional[int,str]=""):
print(a)