语法:变量:类型
语法: type:类型
函数语法: def func(形参名:类型,形参名:类型...):
pass返回值语法: def func(形参名:类型,形参名:类型...) -> 返回值类型:
pass
Union类型
语法:Union[类型,类型...]
先导包:from typing import Union
# 变量类型注解
import json
import random
# 基础数据注解
var_1: int = 10
var2_2: str = "a"
var_3: bool = True
# 类对象注解
class Student:
pass
stu: Student = Student()
# 容器注解
my_list: list = [1, 2, 3]
my_list1: list[int] = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_tuple1: tuple[str, int, bool] = ("a", 1, True)
my_set: set = {1, 2, 3}
my_set: set[int] = {1, 2, 3}
my_dict: dict = {"a": 1}
my_dict: dict[str, int] = {"a": 1}
my_str: str = "a"
# 注释中进行类型注解
var_01 = random.randint(1, 20) # type:int
var_02 = json.loads('{"name":"xiaoming"}') # type:dict
def func():
pass
var_03 = func() # type:int
def add(x: int, y: int): # 函数进行类型注解
return x + y
def add1(data: list) -> list: # 返回值进行类型注解
return data
add(1, 2)
add1([1, 2])
from typing import Union
my_list1: list[Union[str, int]] = [1, 2, "a", "b"]
my_dict1: dict[str, Union[str, int]] = {"a": 1, "b": "qq"}
def func(data: Union[int, str]) -> Union[int, str]:
pass
func(1, "a")