Python 类型注释核心知识点:变量、函数 / 方法与 Union 类型分步解析
在 Python 中,类型注释(Type Hints)是一种可选的语法,用于指定变量、函数参数和返回值的预期类型。它有助于提高代码的可读性和可维护性,并能让静态类型检查工具(如 mypy
)在运行前检测潜在的类型错误。
一、变量的类型注释
变量的类型注释用于指定变量预期的类型,语法为:变量名: 类型 = 值
(赋值可选)。
1.基本类型注释
# 字符串
name: str = "Alice"# 整数
age: int = 25# 浮点数
height: float = 1.68# 布尔值
is_active: bool = True# None类型(表示空值)
empty_value: None = None
2.容器类型注释(Python 3.9+ 推荐写法)
# 列表(元素为int类型)
numbers: list[int] = [1, 2, 3, 4]# 字典(键为str类型,值为int类型)
user_info: dict[str, int] = {"age": 25, "score": 90}# 元组(固定位置的类型,第一个为str,第二个为int)
person: tuple[str, int] = ("Bob", 30)# 集合(元素为str类型)
hobbies: set[str] = {"reading", "coding"}
3.注意点:
- 变量未赋值时也可单独写类型注释:
data: list[str]
- 类型注释不影响 Python 的动态类型特性,解释器运行时会忽略注释
- 容器类型需明确标注内部元素类型(如
list[int]
而非list
)
二、函数和方法的类型注释
函数 / 方法的类型注释包括参数类型和返回值类型,语法为:
def 函数名(参数1: 类型1, 参数2: 类型2 = 默认值) -> 返回值类型:...
1. 普通函数注释
# 无返回值(返回None)
def print_message(message: str) -> None:print(message)# 有返回值
def add(a: int, b: int) -> int:return a + b# 带默认参数
def greet(name: str = "Guest") -> str:return f"Hello, {name}!"
2. 复杂参数类型
# 列表参数和列表返回值
def filter_positive(numbers: list[int]) -> list[int]:return [n for n in numbers if n > 0]# 可变参数(*args)
def sum_all(*args: float) -> float:return sum(args)# 关键字参数(**kwargs)
def print_user(** kwargs: str) -> None:for key, value in kwargs.items():print(f"{key}: {value}")
3. 类方法注释
class Calculator:# 实例方法:self无需标注类型(或标注为Self,需从typing导入)def multiply(self, a: int, b: int) -> int:return a * b# 类方法:cls标注为Type[当前类]@classmethoddef create_instance(cls: type["Calculator"]) -> "Calculator":return cls()
三、Union 类型(联合类型)
Union
用于表示变量 / 参数可以是多种类型中的一种,需从 typing
模块导入(Python 3.10+ 可简化为 |
语法)。
1. 基本用法(Python 3.9 及以下)
from typing import Union# 变量可以是int或str
id: Union[int, str] = 100 # 合法
id = "user123" # 也合法# 函数参数可以是int或float,返回值可以是int、float或str
def format_number(n: Union[int, float]) -> Union[int, float, str]:if n < 0:return "Negative"return n
2. Python 3.10+ 简化写法(推荐)
# 用 | 替代 Union
id: int | str = 100
id = "user123" # 合法def format_number(n: int | float) -> int | float | str:if n < 0:return "Negative"return n
3. 常见使用场景
处理可能为 None
的值(结合 Optional
,而 Optional[T]
等价于 T | None
):
# 等价于 Optional[str]
username: str | None = Nonedef get_name() -> str | None:return "Alice" if some_condition else None
处理多种可能的输入类型:
def process_input(data: list[int] | tuple[int, ...] | set[int]) -> list[int]:return sorted(list(data))
总结
- 变量注释:
变量名: 类型
,明确变量预期类型 - 函数注释:
def 函数(参数: 类型) -> 返回类型
,标注参数和返回值类型 - Union 类型:表示 "或" 关系,Python 3.10+ 推荐用
|
符号,用于标注多种可能的类型
通过类型注释,配合 mypy
等工具可以在开发阶段检测类型错误,尤其适合大型项目和团队协作。