Python的类型注解是一种使用类型提示(type hints)的方法,它可以帮助开发者在编写代码时进行类型检查,以及提供代码自动完成和文档等额外的功能。类型注解是提示性的,并不是强制决定性的。
- 基础用法:变量:类型
my_str: str = "字符串"
my_int: int = 20
my_float: float = 3.1415926
my_bool: bool = False
- 为容器进行注解:
my_list: list = ["小明", "小李", 3]
my_tuple: tuple = ("小明", "小李", 3)
my_set: set = {"小明", "小李", 3}
my_dict: dict = {"名字": "小明", "年龄": 18, "爱好": "敲代码"}
- 详细注解:
my_list: list[int] = [1, 2, 3]
my_tuple: tuple[str, bool, int] = ("小明", True, 3)
my_set: set[str] = {"小明", "小李", "小美"}
my_dict: dict[str, str] = {"名字": "小明", "年龄": "18", "爱好": "敲代码"}
# * 元组类型设置详细注解需要将每个元素的类型都标记出来
# * 字典类型设置详细注解,需要设置两个,一个为key一个为value
- 在注释中使用注解:
let_str = "字符串" # type: str
let_list = [1, 2, 3] # type: list[int]
- 类对象进行注解:
class Student:
pass
stu: Student = Student()
- 对函数进行类型注解:
- 直接在参数后边使用:类型。
- -> int,表示该函数返回一个int类型的变量。
def add(x: int, y: int) -> int:
return x + y
- Union类型注解,联合类型,使用Union需要先从typing包中引入,用于表示一个变量可以接受多种类型的值。
from typing import Union
# 数组容器使用
let_list: list[Union[str, int]] = [1, "小明", 3]
my_dict: dict[str, Union[str, int]] = {"名字": "小明", "年龄": 18, "爱好": "敲代码"}
# 方法参数及返回值使用
def add(x: Union[int, str]) -> Union[int, str]:
return x