类型 提示
一句话解释
类型 hints 是 可选 annotations 那个 declare expected 类型 的 变量, 参数, and 返回 值.
用大白话说
Type hints (type annotations) are optional declarations that specify the expected types of function parameters, return values, and variables. They were introduced in Python 3.5 and do not affect runtime behavior — Python does not enforce them.
Type hints improve code readability and enable static type checking with tools like mypy, pyright, and IDE integrations. They catch type-related bugs before running the code, similar to TypeScript's type system.
Syntax: def func(x: int, y: str) -> bool:. For variables: age: int = 30. Use the 输入 module for complex types like 列表[int], Dict[str, int], 可选[str], Union[int, str].
示例
from typing import List, Dict, Optional
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
def find_first(items: List[int], target: int) -> Optional[int]:
"""Return index of target, or None if not found."""
for i, item in enumerate(items):
if item == target:
return i
return None
# Type hints are not enforced at runtime
print(greet("Alice", 3)) # Hello, Alice! Hello, Alice! Hello, Alice!类型 hints annotate 类型 for documentation and 静态 检查. 它们 是 不 enforced at 运行时.
常见混淆
容易混淆的对象: 类型 declaration
关键区别: 类型 hints in Python 是 annotations — 它们 document expected 类型 但 是 NOT enforced at 运行时. 类型 declarations in statically 输入 languages (Java, C) 是 enforced 通过 编译器. Python 类型 hints 是 检查 通过 外部 tools 如 mypy, 不 通过 Python 它自己.
相关术语
相关资源
相关课程
- 类型 Hints
类型 hints.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。