1. 类型注解
3.5 版本时引入类型注解,提供数据类型的注解,方便第三方工具进行代码提示;
注意类型注解随着版本的更替情况,具体可参考官方文档中的说明;
1.1 变量类型注解
无法直接看出的需要类型注解
list1: list = [1, 2, 3] # 不需要
var1 = func_demo() # 需要
var1: list = func_demo() # 添加后的形式
1.变量:类型
a: int = 10
b: float = 2.163
# 类注解
class Student
pass
stu: Student = Student()
list1: list = [1, 2, 3]
dict1: dict = {"w1":w1, "b1":b1}
容器类型注解
list_con: list[int] = [10, 9, 8]
tuple_con: tuple[str, int, bool] = ["sting", 100, Fasle]
dict_con: dict[str, int] = {"dcitory01": 1000} #key: value
2.注释进行类型注解
#type: 类型
var1 = 90 # type: int
1.2 函数和方法的类型注解
- 箭头
->
返回值类型注解
def demo_add(x: int, y: int):
return x + y
# 返回值类型进行类型注解 ->
def demo_func(data: list) -> tuple:
pass
1.3 Union联合类型注解
- 包的导入
- 中括号
from typing import Union
# 联合类型注解,适用于多个不同类型
list_union: list[Union[str, int]] = [1, 2, "string"]
# value 包含两种类型str 和 int
dict_union: dict[str, Union[str, int]] = {"name": "union", "age": 35}