var1: int = 10
var2: str = "123"
var3: dict = {"it": 12} # 基本类型注释
class Student():
pass
var4: Student = Student() # 类对象类型注释
def func():
return 10
var5: int = func() # 函数返回值注释
函数和方法类型注解:
# 形参类型注解
def add(x: int, y: int):
return x+y
add()
# 返回值类型注解
def add(x, y) ->int :
return x+y
union类型:
使用union类型必须先导包
from typing import Union
var1: list[Union[int,str]] = [1, "chen"]
my_dict:dict[str,Union[str, int]] = {"name":"chen", "age": 18}
# 函数使用union
def my_func(data: Union[int, str]) ->Union[int,str]:
pass
my_func()