师从黑马程序员
类型注解的语法
类型注释的限制
import json
import randomvar_1 : int=10
var_2 : str="itheima"
var_3 : bool=Trueclass Student:pass
stu :Student=Student()my_list:list =[1,2,3]
my_tuple:tuple=(1,2,3)
my_dict:dict={"itheima":666}my_list:list[int] =[1,2,3]
my_tuple:tuple[int,str,bool]=(1,"itheima",True)
my_dict:dict[str,int]={"itheima":666}var_1=random.randint(1,10) #type: int
var_2=json.loads('{"name":"zhangsan"}') #type:dict[str,str]
def func():return 10
var_3=func() #type:intvar_4:int="ithema"
var_5:int=123 #不会报错
函数和方法的类型注解
形式参数注解
返回值注解
def add(x:int,y:int):return x+ydef func(data:list)->list:return dataprint(func(1))
Union类型注解
变量
函数
from typing import Union#导包my_list:list[Union[int,str]]=[1,2,"itheima","itcast"]def func(data:Union[int,str])->Union[int,str]:pass
func()
若有侵权,请联系作者