⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

Python 类型提示入门

学习如何使用类型提示(Type Hints)提高代码可读性和可维护性,支持静态类型检查。 · 难度:入门 · +15XP

什么是类型提示?

Python 3.5+ 引入了类型提示(Type Hints),允许你在函数参数、返回值和变量上标注期望的类型。类型提示不会影响运行时行为,但可以帮助开发者理解代码意图,并通过工具(如 mypy、Pyright)进行静态类型检查,提前发现潜在错误。

基本语法

def greet(name: str) -> str:
    return f"你好,{name}"

age: int = 25 height: float = 1.75 is_student: bool = True

常见类型与组合

类型示例说明
int, float, str, booldef add(a: int, b: int) -> int基本类型
List, Dict, Tuple, Setfrom typing import List
def process(items: List[int]) -> None
容器类型,需要从 typing 导入
Optionalfrom typing import Optional
def find(user_id: int) -> Optional[str]
表示值可能为 None
Unionfrom typing import Union
def parse(data: Union[str, bytes]) -> dict
多个类型中的任意一个
Anyfrom typing import Any
def log(msg: Any) -> None
任意类型(放弃检查)

函数注解进阶

from typing import List, Optional

def get_first_item(items: List[int]) -> Optional[int]: if items: return items[0] return None

# 类型别名 def Vector = List[float] def scale(vec: Vector, factor: float) -> Vector: return [x * factor for x in vec]

类型检查工具

安装 mypy:pip install mypy,然后运行 mypy your_script.py。如果代码中存在类型冲突,mypy 会报告错误。

练习提示

修改下方代码,为函数 calculate_average 添加正确的类型提示:参数 numbers 应该是 List[float],返回值应为 float。同时为变量 result 添加类型注解。

最佳实践

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 152 篇
0 完成
🔥 0