全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

Python 类型别名

类型别名用于简化复杂类型注解,增强代码可读性。

基本类型别名

Python
from typing import List, Dict, Tuple

# 简单别名
Vector = List[float]
Matrix = List[Vector]

# 使用别名
def normalize(v: Vector) -> Vector:
    total = sum(x ** 2 for x in v) ** 0.5
    return [x / total for x in v]

v: Vector = [1.0, 2.0, 3.0]
m: Matrix = [[1, 2], [3, 4]]

复合类型别名

Python
from typing import Dict, List, Tuple, Union

# 用户数据类型
UserData = Dict[str, Union[str, int, bool]]

user: UserData = {
    'name': 'Alice',
    'age': 25,
    'active': True
}

# 嵌套复合类型
Record = Tuple[str, int, Dict[str, List[int]]

record: Record = ('Alice', 25, {'scores': [90, 85, 88]})

函数类型别名

Python
from typing import Callable

# 回调函数别名
Callback = Callable[[int, str], bool]

def register(handler: Callback) -> None:
    print("注册回调")

def my_handler(id: int, name: str) -> bool:
    return id > 0

register(my_handler)

TypeAlias 显式标注

Python
from typing import TypeAlias

# Python 3.10+ 显式类型别名
Vector: TypeAlias = List[float]
Matrix: TypeAlias = List[Vector]

# 区分普通赋值和类型别名
Age = int  # 普通变量赋值
Age: TypeAlias = int  # 类型别名

泛型类型别名

Python
from typing import TypeVar, Generic, List, TypeAlias

T = TypeVar('T')

# 泛型别名
Container: TypeAlias = List[T]

def process(items: Container[int]) -> Container[int]:
    return [x * 2 for x in items]

嵌套类型别名

Python
from typing import TypedDict, List, TypeAlias

class Point(TypedDict):
    x: float
    y: float

# 嵌套别名
Path: TypeAlias = List[Point]
Shape: TypeAlias = Dict[str, Path]

path: Path = [{'x': 0, 'y': 0}, {'x': 10, 'y': 10}]
shape: Shape = {'line': path}

Optional 别名

Python
from typing import Optional, TypeAlias

# 可选类型别名
MaybeInt: TypeAlias = Optional[int]
MaybeStr: TypeAlias = Optional[str]

def parse(value: str) -> MaybeInt:
    try:
        return int(value)
    except ValueError:
        return None

result: MaybeInt = parse('123')

Union 别名

Python
from typing import Union, TypeAlias

# 联合类型别名
Number: TypeAlias = Union[int, float]
ID: TypeAlias = Union[int, str]

def calculate(a: Number, b: Number) -> Number:
    return a + b

def find(id: ID) -> Optional[str]:
    return 'found'

业务类型别名

Python
from typing import TypedDict, List, TypeAlias

# 业务领域类型别名
class User(TypedDict):
    id: int
    name: str
    email: str

class Order(TypedDict):
    order_id: str
    user_id: int
    amount: float

Users: TypeAlias = List[User]
Orders: TypeAlias = List[Order]

def process_users(users: Users) -> Orders:
    return [{'order_id': 'ORD001', 'user_id': u['id'], 'amount': 100.0}
            for u in users]

类型别名 vs 类型变量

Python
from typing import TypeAlias, TypeVar, List

# 类型别名:固定类型
Vector: TypeAlias = List[float]

# 类型变量:可变类型
T = TypeVar('T')
Container = List[T]  # 泛型,T 可变化

# 别名使用
v: Vector = [1.0, 2.0]  # 固定 float 列表

# 泛型使用
c_int: Container[int] = [1, 2]
c_str: Container[str] = ['a', 'b']

要点总结

  • 类型别名简化复杂类型注解
  • Alias = ComplexType 定义别名
  • Python 3.10+ 用 TypeAlias 显式标注
  • 支持嵌套、泛型、函数类型别名
  • 别名提高代码可读性和一致性
  • 泛型别名配合 TypeVar 使用
  • 业务领域可定义语义化类型别名
  • 类型别名是静态类型,不创建新类

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 复合类型注解
下一篇 → Python 类型检查工具
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库