🐍

Python 完全指南

从语言诞生到AI时代霸主 - 最全面的Python知识体系

📜 发展历史 🎯 设计哲学 💻 完整语法 🚀 高级特性 🔥 AI生态 🏗️ 工程实践 📦 实战项目

一、Python 发展简史

从圣诞节的个人项目到AI时代的霸主语言,Python用30年时间改变了编程世界

🎄 诞生于荷兰的圣诞节

1989年12月,荷兰程序员 Guido van Rossum 在阿姆斯特丹的圣诞假期感到无聊, 决定为自己开发的 ABC 教学语言编写一个继承者。他希望创造一门既强大又易读的编程语言。

Python 这个名字来源于 Guido 喜爱的英国喜剧团体 Monty Python(巨蟒剧团), 而非蟒蛇🐍。这个名字体现了 Guido 希望编程应该是有趣而非枯燥的理念。

"我选择Python作为工作项目的名字,因为我心情不太好……我需要一个简短、独特且略带神秘的名字。" — Guido van Rossum

📅 重要版本里程碑

1991.02 Python 0.9.0

首次发布到 alt.sources 新闻组,包含了类、异常处理、函数和模块系统

类与继承 异常处理 模块系统
1994.01 Python 1.0

第一个正式版本,引入了 lambda、map、filter、reduce 等函数式编程特性

函数式编程 Lambda表达式
2000.10 Python 2.0

引入列表推导式、垃圾回收机制、Unicode支持,开始社区驱动开发

列表推导式 GC垃圾回收 Unicode
2008.12 Python 3.0 🔄

重大突破!不向后兼容的重大更新,修复了很多设计缺陷(print函数化、字符串Unicode化等)

不兼容2.x print函数 默认Unicode
2009-2020 Python 2/3 混乱期

长达11年的版本分裂,社区和企业在 Python 2 和 3 之间艰难抉择,大量库需要重写迁移

2016.12 Python 3.6 ⭐

引入 f-string(格式化字符串字面量),性能大幅提升,类型注解成熟

f-string 异步生成器 变量注解
2020.01.01 Python 2.7 停止维护 ⚰️

Python 2 正式退出历史舞台,Python 3 成为唯一选择,统一了社区

2022.10 Python 3.11 🚀

性能提升10-60%,更好的错误提示,异步性能大幅提升

性能革命 错误追踪 异步优化
2023.10 Python 3.12 (当前) 🔥

更快的性能、改进的f-string、类型参数语法、更好的错误消息

持续优化 PEP 701 类型泛型

👨‍💻 "仁慈的独裁者" - Guido van Rossum

1991-2018: 担任 Python 的 BDFL(Benevolent Dictator For Life,终身仁慈独裁者),对所有重大决策拥有最终决定权

2018年7月: 在 PEP 572 (海象运算符:=) 争议后宣布退位,不再担任BDFL

工作经历: Google (2005-2012) → Dropbox (2013-2019) → Microsoft (2020-至今)

"我的目标是让Python成为第二好的语言 — 因为每个人的第一选择都不同。" — Guido

二、Python 设计哲学

The Zen of Python - Python之禅

🧘

The Zen of Python

by Tim Peters (PEP 20)

>>> import this

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

Now is better than never.

Although never is often better than *right* now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!

📖 可读性至上

"Readability counts" - Python强制使用缩进,变量命名清晰,让代码像散文一样易读

# Python的方式 - 清晰直观 if user.is_authenticated: show_dashboard() else: redirect_to_login()

🎯 显式优于隐式

"Explicit is better than implicit" - 代码意图应该明确,避免魔法和隐藏行为

# 好 - 明确导入 from datetime import datetime # 不好 - 隐式导入 from datetime import *

🛤️ 唯一明显的方法

"There should be one obvious way to do it" - 减少选择困难,提供最佳实践

# Python推荐的方式 with open('file.txt') as f: content = f.read() # 自动关闭文件,优雅且安全

⚡ 实用性胜过纯粹性

"Practicality beats purity" - 现实世界的问题优先,不追求完美主义

# 接受不完美但实用的解决方案 # GIL虽然限制并发,但简化了实现 # 动态类型虽然慢,但提高了开发效率

🎨 Python的独特魅力

🐍

强制缩进

用缩进代替大括号,强制代码整洁,这是Python最具争议但也最成功的设计

🔀

动态类型

变量无需声明类型,鸭子类型让代码更灵活,开发速度更快

🎁

包含电池

"Batteries Included" - 标准库功能丰富,开箱即用,无需大量第三方依赖

🌍

多范式

支持面向对象、函数式、过程式编程,让你用最舒服的方式写代码

🔓

开源免费

PSF许可证,完全开源,可自由用于商业项目,庞大的社区支持

⚙️

高扩展性

可以用C/C++扩展性能关键部分,兼顾开发效率和运行性能

三、Python 生态系统全景

从包管理到AI框架,Python拥有最完整的生态

📦 包管理与环境

pip

Python官方包管理工具

pip install requests

conda

跨语言包和环境管理

conda create -n myenv

poetry

现代化依赖管理

poetry add fastapi

🌐 Web开发框架

Django

全栈框架,包含一切

Flask

轻量级,灵活扩展

FastAPI

现代异步高性能

Tornado

异步Web服务器

📊 数据科学生态

核心计算

  • • NumPy - 数值计算
  • • Pandas - 数据分析
  • • SciPy - 科学计算

可视化

  • • Matplotlib - 基础绘图
  • • Seaborn - 统计图表
  • • Plotly - 交互图表

机器学习

  • • Scikit-learn - 经典ML
  • • XGBoost - 梯度提升
  • • LightGBM - 快速训练

🧠 深度学习框架

PyTorch ⭐

Meta开发,研究首选

动态图

TensorFlow

Google开发,生产级

静态图

JAX

NumPy+自动微分

JIT编译

🛠️ 开发工具

  • Jupyter - 交互式笔记本
  • VSCode - 最流行IDE
  • PyCharm - 专业Python IDE
  • Black - 代码格式化
  • Pytest - 单元测试

📚 其他领域

  • Requests - HTTP请求
  • BeautifulSoup - 网页解析
  • Selenium - 浏览器自动化
  • Celery - 异步任务队列
  • SQLAlchemy - ORM框架

四、Python完整语法教程

通过构建一个任务管理系统,学习Python的所有核心语法

📝

TodoMaster - 任务管理系统

从命令行到Web API,逐步构建完整应用

✅ 功能特性

创建、查看、更新、删除任务

🎯 覆盖语法

从基础到高级的所有特性

🚀 渐进式

每个版本增加新特性

阶段1:基础语法 - 命令行版本

变量、数据类型、控制流、函数

# todo_v1.py - 最基础的任务管理器 # === 1. 变量与数据类型 === # 使用列表存储任务 todos = [] # 空列表 todo_id = 1 # 任务ID计数器 # === 2. 函数定义 === def add_task(title, description=""): """添加新任务""" global todo_id # 字典存储任务信息 task = { "id": todo_id, "title": title, "description": description, "completed": False } todos.append(task) todo_id += 1 # f-string 格式化输出 print(f"✅ 任务 '{title}' 已添加!") return task def list_tasks(): """列出所有任务""" if not todos: # 判断列表是否为空 print("📋 暂无任务") return print(f"\n📋 共有 {len(todos)} 个任务:\n") # for循环遍历 for task in todos: status = "✅" if task["completed"] else "⭕" print(f"{status} [{task['id']}] {task['title']}") # 如果有描述,显示描述 if task["description"]: print(f" 💬 {task['description']}") def complete_task(task_id): """标记任务为完成""" # 使用enumerate获取索引和值 for i, task in enumerate(todos): if task["id"] == task_id: todos[i]["completed"] = True print(f"✅ 任务 '{task['title']}' 已完成!") return # 未找到任务 print(f"❌ 未找到ID为 {task_id} 的任务") def delete_task(task_id): """删除任务""" for i, task in enumerate(todos): if task["id"] == task_id: deleted = todos.pop(i) # pop删除并返回 print(f"🗑️ 任务 '{deleted['title']}' 已删除!") return print(f"❌ 未找到ID为 {task_id} 的任务") # === 3. 主程序循环 === def main(): """主函数""" print("🎯 TodoMaster v1.0") print("=" * 30) # while 无限循环 while True: print("\n命令: [a]添加 [l]列表 [c]完成 [d]删除 [q]退出") cmd = input("请输入命令: ").strip().lower() # if/elif/else 条件判断 if cmd == 'a': title = input("任务标题: ") desc = input("任务描述(可选): ") add_task(title, desc) elif cmd == 'l': list_tasks() elif cmd == 'c': try: task_id = int(input("任务ID: ")) complete_task(task_id) except ValueError: print("❌ 请输入有效的数字ID") elif cmd == 'd': try: task_id = int(input("任务ID: ")) delete_task(task_id) except ValueError: print("❌ 请输入有效的数字ID") elif cmd == 'q': print("👋 再见!") break # 跳出循环 else: print("❌ 无效命令") # === 4. 程序入口 === if __name__ == "__main__": main()

💡 这段代码涵盖:

  • ✓ 变量定义(数字、字符串、列表、字典)
  • ✓ 函数定义与参数(默认参数)
  • ✓ 条件语句(if/elif/else)
  • ✓ 循环(for、while)
  • ✓ 字符串格式化(f-string)
  • ✓ 列表操作(append、pop、enumerate)
  • ✓ 异常处理(try/except)
  • ✓ 用户输入(input)

阶段2:面向对象 - 类与对象

重构为面向对象设计

# todo_v2.py - 面向对象版本 from datetime import datetime from typing import List, Optional # === 1. 定义Task类 === class Task: """任务类 - 封装任务的属性和行为""" # 类变量(所有实例共享) _id_counter = 1 def __init__(self, title: str, description: str = ""): """构造函数""" self.id = Task._id_counter Task._id_counter += 1 self.title = title self.description = description self.completed = False self.created_at = datetime.now() self.completed_at: Optional[datetime] = None def complete(self): """标记任务为完成""" self.completed = True self.completed_at = datetime.now() def to_dict(self) -> dict: """转换为字典""" return { "id": self.id, "title": self.title, "description": self.description, "completed": self.completed, "created_at": self.created_at.isoformat(), "completed_at": self.completed_at.isoformat() if self.completed_at else None } def __str__(self) -> str: """字符串表示(用于打印)""" status = "✅" if self.completed else "⭕" return f"{status} [{self.id}] {self.title}" def __repr__(self) -> str: """详细表示(用于调试)""" return f"Task(id={self.id}, title='{self.title}', completed={self.completed})" @staticmethod def from_dict(data: dict) -> 'Task': """从字典创建Task实例(用于反序列化)""" task = Task(data['title'], data.get('description', '')) task.id = data['id'] task.completed = data['completed'] return task # === 2. 定义TodoManager类 === class TodoManager: """任务管理器类 - 管理所有任务""" def __init__(self): self._tasks: List[Task] = [] # 私有属性(约定) def add_task(self, title: str, description: str = "") -> Task: """添加任务""" task = Task(title, description) self._tasks.append(task) print(f"✅ 任务 '{title}' 已添加!") return task def get_task(self, task_id: int) -> Optional[Task]: """根据ID获取任务""" for task in self._tasks: if task.id == task_id: return task return None def list_tasks(self, show_completed: bool = True): """列出任务""" tasks = self._tasks if show_completed else [ t for t in self._tasks if not t.completed ] if not tasks: print("📋 暂无任务") return print(f"\n📋 共有 {len(tasks)} 个任务:\n") for task in tasks: print(task) # 调用__str__ if task.description: print(f" 💬 {task.description}") def complete_task(self, task_id: int) -> bool: """完成任务""" task = self.get_task(task_id) if task: task.complete() print(f"✅ 任务 '{task.title}' 已完成!") return True print(f"❌ 未找到ID为 {task_id} 的任务") return False def delete_task(self, task_id: int) -> bool: """删除任务""" task = self.get_task(task_id) if task: self._tasks.remove(task) print(f"🗑️ 任务 '{task.title}' 已删除!") return True print(f"❌ 未找到ID为 {task_id} 的任务") return False @property # 属性装饰器 def total_tasks(self) -> int: """总任务数""" return len(self._tasks) @property def completed_tasks(self) -> int: """已完成任务数""" return sum(1 for t in self._tasks if t.completed) def __len__(self) -> int: """支持len()函数""" return self.total_tasks def __iter__(self): """支持迭代""" return iter(self._tasks) # === 3. 使用示例 === if __name__ == "__main__": manager = TodoManager() # 添加任务 manager.add_task("学习Python面向对象", "理解类、对象、封装") manager.add_task("完成项目") # 列出任务 manager.list_tasks() # 使用property print(f"\n📊 统计: {manager.completed_tasks}/{manager.total_tasks} 已完成") # 完成任务 manager.complete_task(1) # 支持len() print(f"总任务数: {len(manager)}") # 支持迭代 print("\n遍历所有任务:") for task in manager: print(f" - {task.title}")

💡 新增特性:

  • ✓ 类定义(class)与构造函数(__init__)
  • ✓ 实例变量与类变量
  • ✓ 方法定义(self参数)
  • ✓ 特殊方法(__str__、__repr__等)
  • ✓ 类型注解(Type Hints)
  • ✓ 属性装饰器(@property)
  • ✓ 私有属性约定(_下划线前缀)
  • ✓ 迭代器协议(__iter__、__len__)

阶段3:文件存储 + 高级特性

上下文管理器、装饰器、生成器、文件IO

完整代码较长,这里展示核心高级特性的应用:

# todo_v3.py - 添加文件存储和高级特性 import json from pathlib import Path from typing import Generator, Callable from functools import wraps import time # === 1. 装饰器 - 记录函数执行时间 === def timer(func: Callable) -> Callable: """装饰器:测量函数执行时间""" @wraps(func) # 保留原函数元数据 def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start print(f"⏱️ {func.__name__} 耗时: {elapsed:.3f}s") return result return wrapper # === 2. 上下文管理器 - 自动保存数据 === class TodoManager: def __init__(self, filename: str = "todos.json"): self.filename = Path(filename) self._tasks: List[Task] = [] self.load_from_file() # 使用上下文管理器自动保存 def __enter__(self): """进入with块""" return self def __exit__(self, exc_type, exc_val, exc_tb): """退出with块,自动保存""" self.save_to_file() return False # 不抑制异常 # === 3. 文件IO === def save_to_file(self): """保存到JSON文件""" data = [task.to_dict() for task in self._tasks] # with语句自动关闭文件 with open(self.filename, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) print(f"💾 数据已保存到 {self.filename}") @timer # 使用装饰器 def load_from_file(self): """从JSON文件加载""" if not self.filename.exists(): return try: with open(self.filename, 'r', encoding='utf-8') as f: data = json.load(f) self._tasks = [Task.from_dict(item) for item in data] print(f"📂 已从 {self.filename} 加载 {len(self._tasks)} 个任务") except json.JSONDecodeError as e: print(f"❌ 文件格式错误: {e}") # === 4. 生成器 - 按条件迭代任务 === def filter_tasks( self, predicate: Callable[[Task], bool] ) -> Generator[Task, None, None]: """生成器:按条件筛选任务""" for task in self._tasks: if predicate(task): yield task # yield使这成为生成器 def pending_tasks(self) -> Generator[Task, None, None]: """生成器:返回未完成的任务""" return self.filter_tasks(lambda t: not t.completed) # === 5. 使用示例 === if __name__ == "__main__": # 使用上下文管理器,自动保存 with TodoManager() as manager: manager.add_task("学习装饰器") manager.add_task("掌握生成器") manager.add_task("理解上下文管理器") # 使用生成器遍历(惰性求值,节省内存) print("\n未完成的任务:") for task in manager.pending_tasks(): print(f" - {task.title}") # 退出with块时自动调用save_to_file() print("\n✅ 程序结束,数据已自动保存")

💡 高级特性:

  • ✓ 装饰器(@decorator)- 函数增强
  • ✓ 上下文管理器(__enter__/__exit__)
  • ✓ 生成器(yield)- 惰性求值
  • ✓ Lambda表达式
  • ✓ 文件IO(with open)
  • ✓ JSON序列化/反序列化
  • ✓ pathlib - 现代路径操作
  • ✓ 异常处理(try/except)

补充:推导式(Comprehension)

Python的优雅语法糖 - 简洁而强大

# === 推导式 - Python的语法糖 === # 1. 列表推导式(List Comprehension) # 基础用法 squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 带条件过滤 evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # 嵌套推导式 matrix = [[i*j for j in range(3)] for i in range(3)] # [[0, 0, 0], [0, 1, 2], [0, 2, 4]] # 2. 字典推导式(Dict Comprehension) # 基础用法 squares_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # 字典反转 original = {'a': 1, 'b': 2, 'c': 3} reversed_dict = {v: k for k, v in original.items()} # {1: 'a', 2: 'b', 3: 'c'} # 带条件 filtered = {k: v for k, v in original.items() if v > 1} # {'b': 2, 'c': 3} # 3. 集合推导式(Set Comprehension) # 去重 unique_chars = {c.lower() for c in "Hello World"} # {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'} # 数学集合 multiples = {x for x in range(20) if x % 3 == 0} # {0, 3, 6, 9, 12, 15, 18} # 4. 生成器表达式(Generator Expression) # 惰性求值,节省内存 gen = (x**2 for x in range(1000000)) # 不会立即计算 # 用于sum等函数 total = sum(x**2 for x in range(10)) # 285 # 5. 实际应用示例 # 处理文件数据 lines = [" hello ", " world ", " python "] cleaned = [line.strip().upper() for line in lines] # ['HELLO', 'WORLD', 'PYTHON'] # 提取数据 users = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 17}, {'name': 'Charlie', 'age': 30} ] adults = [u['name'] for u in users if u['age'] >= 18] # ['Alice', 'Charlie']

💡 推导式优势:

  • ✓ 代码更简洁优雅
  • ✓ 性能通常更好
  • ✓ 可读性强(熟悉后)
  • ✓ 支持嵌套和条件
  • ✓ 生成器表达式节省内存
  • ✓ Pythonic风格的体现

🎓 语法学习总结

通过TodoMaster项目,我们系统学习了Python的核心语法:

✅ 基础

变量、数据类型、控制流、函数、异常处理

✅ 面向对象

类、对象、继承、多态、特殊方法

✅ 高级特性

装饰器、生成器、上下文管理器、推导式

五、Python 高级特性

掌握这些特性,代码水平再上台阶

🎨 装饰器完全指南

from functools import wraps # 1. @property - 属性装饰器 class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value < 0: raise ValueError("半径不能为负") self._radius = value @property def area(self): return 3.14 * self._radius ** 2 # 2. @classmethod - 类方法 class Person: count = 0 # 类变量 def __init__(self, name): self.name = name Person.count += 1 @classmethod def get_count(cls): return f"共有 {cls.count} 个实例" @classmethod def from_string(cls, data_str): # 工厂方法 name = data_str.split(',')[0] return cls(name) # 3. @staticmethod - 静态方法 class MathUtils: @staticmethod def add(a, b): return a + b @staticmethod def is_even(n): return n % 2 == 0 # 使用示例 c = Circle(5) print(c.area) # 78.5(作为属性访问) print(Person.get_count()) # 类方法 print(MathUtils.add(1, 2)) # 静态方法

🚨 异常处理完全指南

# 1. try/except/else/finally 完整结构 try: f = open('data.txt', 'r') data = f.read() result = int(data) except FileNotFoundError: print("文件不存在") except ValueError: print("数据格式错误") except Exception as e: print(f"其他错误: {e}") else: # 没有异常时执行 print(f"成功读取: {result}") finally: # 总是执行(清理资源) if 'f' in locals(): f.close() # 2. 自定义异常 class ValidationError(Exception): def __init__(self, field, message): self.field = field self.message = message super().__init__(f"{field}: {message}") def validate_age(age): if age < 0: raise ValidationError('age', '年龄不能为负') # 3. 异常链 try: validate_age(-5) except ValidationError as e: print(f"验证失败: {e.field} - {e.message}")

⚡ 异步编程(async/await)

import asyncio async def fetch_data(url: str): # 模拟异步IO操作 await asyncio.sleep(1) return f"Data from {url}" async def main(): # 并发执行多个任务 tasks = [ fetch_data("api1.com"), fetch_data("api2.com"), fetch_data("api3.com") ] results = await asyncio.gather(*tasks) print(results) asyncio.run(main())

🏷️ 数据类(dataclass)

from dataclasses import dataclass, field from typing import List @dataclass class Product: name: str price: float tags: List[str] = field(default_factory=list) def discount(self, percent: float) -> float: return self.price * (1 - percent/100) # 使用示例 product = Product("笔记本", 5999.0, ["电子", "办公"]) print(product.discount(10)) # 5399.1

🔮 元编程(Metaclass)

# 元类 - 控制类的创建 class Singleton(type): """单例模式元类""" _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls] class Database(metaclass=Singleton): """数据库连接类(单例)""" def connect(self): print("Connecting to database...") # 使用示例 db1 = Database() db2 = Database() print(db1 is db2) # True - 单例模式,两个变量指向同一实例

六、Python AI/ML 技术栈

为什么Python是AI时代的第一语言

🧠 主流深度学习框架

PyTorch

Meta开发,动态计算图,研究首选

import torch import torch.nn as nn class NeuralNet(nn.Module): """简单的神经网络""" def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 50) self.fc2 = nn.Linear(50, 1) def forward(self, x): x = torch.relu(self.fc1(x)) return self.fc2(x) # 使用示例 model = NeuralNet() x = torch.randn(32, 10) # batch_size=32, input_size=10 output = model(x)

TensorFlow

Google开发,生产部署强,移动端支持好

import tensorflow as tf # 构建模型 model = tf.keras.Sequential([ tf.keras.layers.Dense( 50, activation='relu', input_shape=(10,) ), tf.keras.layers.Dense(1) ]) # 编译模型 model.compile( optimizer='adam', loss='mse' ) # 训练模型 model.fit(X_train, y_train, epochs=10)

🔄 完整的AI开发工作流

📊
数据处理
Pandas
NumPy
Polars
🔬
特征工程
Scikit-learn
Feature-engine
Category Encoders
🧠
模型训练
PyTorch
TensorFlow
XGBoost
🚀
模型部署
FastAPI
TorchServe
ONNX

🤖 大语言模型(LLM)开发

Transformers

HuggingFace开发,预训练模型库

from transformers import pipeline generator = pipeline( "text-generation", model="gpt2" )

LangChain

LLM应用开发框架

from langchain import OpenAI llm = OpenAI() response = llm("你好")

LlamaIndex

RAG与知识库

from llama_index import VectorStore index = VectorStore.from_docs(docs)

七、Python 工程化最佳实践

从玩具项目到生产系统

📁 标准项目结构

myproject/ ├── src/ │ ├── __init__.py │ ├── main.py │ ├── models/ │ ├── api/ │ └── utils/ ├── tests/ │ ├── __init__.py │ ├── test_models.py │ └── test_api.py ├── docs/ ├── .gitignore ├── pyproject.toml ├── requirements.txt └── README.md

关键文件说明:

  • pyproject.toml - 项目配置文件
  • requirements.txt - 依赖列表
  • tests/ - 单元测试目录
  • docs/ - 文档目录
  • __init__.py - 包标识文件

🛠️ 代码质量工具链

Black

代码格式化

black .

isort

导入排序

isort .

Pylint

代码检查

pylint src/

MyPy

类型检查

mypy src/

✅ 测试驱动开发(TDD)

# tests/test_calculator.py import pytest from src.calculator import Calculator def test_add(): calc = Calculator() assert calc.add(2, 3) == 5 def test_divide_by_zero(): calc = Calculator() with pytest.raises(ZeroDivisionError): calc.divide(10, 0) # 运行测试:pytest tests/ -v --cov=src

⚡ 性能优化技巧

1. 使用内置函数

# 慢 result = [] for i in range(1000): result.append(i*2) # 快30% result = [i*2 for i in range(1000)]

2. 避免重复计算

# 使用缓存 from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)

🎯 Python 学习路线图

从零基础到AI工程师的完整路径

1️⃣

基础阶段

  • • 语法基础
  • • 数据结构
  • • 控制流
  • • 函数编程
⏱️ 2-4周
2️⃣

进阶阶段

  • • 面向对象
  • • 文件IO
  • • 异常处理
  • • 模块与包
⏱️ 4-6周
3️⃣

实战阶段

  • • Web开发
  • • 数据分析
  • • 爬虫技术
  • • 自动化脚本
⏱️ 8-12周
4️⃣

AI专精

  • • 机器学习
  • • 深度学习
  • • LLM应用
  • • 模型部署
⏱️ 持续学习