Python 类型注解
学习Type Hints · 难度:进阶 · +15XP
Python 类型注解
Python 是动态类型语言,但从 Python 3.5 开始引入了类型注解(Type Hints)机制。类型注解不会影响程序运行,但可以借助 IDE(如 PyCharm、VS Code)和静态类型检查工具(如 mypy)在开发阶段发现类型错误,提升代码可读性和可维护性。
基本类型注解
# 变量类型注解
name: str = 'Alice'
age: int = 25
height: float = 1.68
is_student: bool = True
# 函数参数和返回值的类型注解
def greet(name: str) -> str:
return f'Hello, {name}!'
def add(a: int, b: int) -> int:
return a + b
# 无返回值使用 None
def log_message(msg: str) -> None:
print(f'[LOG] {msg}')
复合类型
from typing import List, Dict, Set, Tuple, Optional, Union
# 列表类型
names: List[str] = ['Alice', 'Bob', 'Charlie']
# 字典类型
student_scores: Dict[str, int] = {'Alice': 95, 'Bob': 87}
# 集合类型
tags: Set[str] = {'python', 'typing', 'tutorial'}
# 元组类型 (固定长度和类型)
point: Tuple[float, float] = (3.5, 2.8)
# 可选类型 (可以是 None)
def find_user(id: int) -> Optional[str]:
users = {1: 'Alice', 2: 'Bob'}
return users.get(id) # 可能返回 None
# 联合类型 (多种类型之一)
def process(value: Union[int, str]) -> str:
return str(value)
高级类型
from typing import Callable, Any, Literal
# 可调用对象类型
def apply(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
# Any 类型 (任意类型)
def parse_json(data: str) -> Any:
import json
return json.loads(data)
# Literal 类型 (精确字面量, Python 3.8+)
def set_mode(mode: Literal['read', 'write', 'append']) -> None:
print(f'模式设置为: {mode}')
类型注解速查表
| 类型 | 用法示例 | 说明 |
|---|---|---|
| str | name: str | 字符串 |
| int | age: int | 整数 |
| float | price: float | 浮点数 |
| bool | active: bool | 布尔值 |
| List[X] | items: List[str] | X 类型列表 |
| Dict[K, V] | scores: Dict[str, int] | 键 K 值 V 字典 |
| Optional[X] | result: Optional[int] | X 或 None |
| Union[X, Y] | val: Union[int, str] | X 或 Y 类型 |