fluent python+interactive scrimba
https://relph1119.github.io/fluent-python/#/
《Python 之禅》(PEP 20)
| 序号 | 格言原文 | 含义解读 |
|---|---|---|
| 1 | Beautiful is better than ugly. | 代码应优雅可读,避免“丑陋”的拼凑。 |
| 2 | Explicit is better than implicit. | 明确胜于隐式:让意图一目了然,少玩“魔法”隐藏逻辑。 |
| 3 | Simple is better than complex. | 简单胜于复杂:用最直接的方法解决问题,避免过度设计。 |
| 4 | Complex is better than complicated. | 当问题本身复杂时,可以有一定复杂度,但不要“累赘”到难以理解。 |
| 5 | Flat is better than nested. | 扁平结构优于深度嵌套:少用多重嵌套,函数/模块拆分要合理。 |
| 6 | Sparse is better than dense. | 稀疏优于稠密:让关键逻辑“透着空隙”,避免一大块难以分辨。 |
| 7 | Readability counts. | 可读性最重要,毕竟代码是给人读的。 |
| 8 | Special cases aren’t special enough to break the rules. | 特殊情况也要遵循相同的规范,别为了个例破坏整体风格。 |
| 9 | Although practicality beats purity. | 实用胜于纯粹:在理想和现实冲突时,倾向于实用的方案。 |
| 10 | Errors should never pass silently. | 错误不要无声地忽略——除非你真的知道要这么做,并要在代码中注明(如捕获后忽略)。 |
| 11 | Unless explicitly silenced. | ——除非你显式地处理或标注“这里故意忽略”。 |
| 12 | In the face of ambiguity, refuse the temptation to guess. | 遇到歧义,要么明确定义行为,要么直接报错,不要凭感觉“瞎猜”。 |
| 13 | There should be one—and preferably only one—obvious way to do it. | 同一件事应有且最好只有一种明显的做法。 |
| 14 | Although that way may not be obvious at first unless you’re Dutch. | ——但如果你是 Guido(荷兰人),可能一开始就觉得理所当然。 |
| 15 | Now is better than never. | 及时行动比一直拖更好。 |
| 16 | Although never is often better than a right now that is worse than nothing_. | ——但如果“做得不好”不如“不做”,宁可等等再做。 |
| 17 | If the implementation is hard to explain, it’s a bad idea. | 如果你都难以向他人解释实现,说明不够优雅或过于复杂,应重构。 |
| 18 | If the implementation is easy to explain, it may be a good idea. | 如果能把实现讲清楚,说明思路清晰、设计合理。 |
| 19 | Namespaces are one honking great idea—let’s do more of those! | 命名空间(模块、包)是伟大的设计,鼓励把不同功能隔离开来,避免全局污染。 |
几个核心 PEP 深度解读
1. PEP 8 — 《Python 代码风格指南》
-
作用:统一团队代码风格,提升可读性。
-
核心要点:
- 缩进 4 空格;
- 行长不超过 79 字符;
- 函数、变量用
snake_case;类用PascalCase; - 导入顺序:标准库 → 第三方库 → 自有模块;
- 空行分隔 top-level 函数/类、方法内部逻辑。
-
学习:安装
flake8、pylint,并在 CI 中强制执行。
2. PEP 257 — 《Docstring 约定》
-
作用:规范函数/类/模块的文档字符串格式。
-
核心要点:
- 三引号
"""…""";首行一句话概述;有参数/返回值时加空行后详细说明; - 支持 Google、NumPy、reST 等风格。
- 三引号
-
学习:在项目中统一一种风格,并用
pydocstyle做检查。
3. PEP 318 — 《Decorators for Functions and Methods》
-
作用:正式引入
@decorator语法。 -
核心要点:
- 装饰器本质是一个可调用对象,接受函数并返回新函数;
- 支持带参数的装饰器(外层再包一层);
- 建议用
functools.wraps保持原函数元信息。
-
学习:自己实现一个“带参数的重试装饰器”,掌握闭包与
wraps用法。
4. PEP 343 — 《The “with” Statement》
-
作用:引入上下文管理协议,简化资源管理。
-
核心要点:
- 类实现
__enter__/__exit__;或用@contextmanager装饰器; - 自动处理异常、清理资源。
- 类实现
-
学习:用
contextlib.contextmanager把一个普通函数变成上下文管理器。
5. PEP 484 / PEP 585 / PEP 604 — 《Type Hints》
-
PEP 484(Python 3.5 引入 typing 模块)
List[int]、Dict[str, Any]、Optional[str]等静态类型。
-
PEP 585(Python 3.9+ 支持内置泛型:
list[int]) -
PEP 604(Python 3.10+ 支持原生联合类型:
str | None) -
作用:在动态语言里也能做静态检查,提高可靠性。
-
学习:用 MyPy 检查大型代码库,逐步补全注解。
6. PEP 557 — 《Data Classes》
-
作用:用
@dataclass快速生成数据容器类(自动生成__init__、__repr__、__eq__等)。 -
核心要点:
- 支持字段默认值、类型、
field()高级选项; frozen=True可生成不可变实例。
- 支持字段默认值、类型、
-
学习:把项目中的“纯数据类”改写成
@dataclass,对比前后代码量。
7. PEP 492 / PEP 525 — 《Async and Await》
- PEP 492(Python 3.5 引入
async def/await) - PEP 525(Python 3.6 引入异步生成器)
- 作用:将协程从 generator hack 演化为一等语法,实现高效 I/O 并发。
- 学习:重构一个阻塞的 HTTP 客户端为
aiohttp+asyncio,体验性能提升。
8. PEP 526 — 《Variable Annotations》
-
作用:为模块级、类属性、局部变量添加类型注解。
-
示例:
count: int = 0 names: list[str] -
学习:给常量、配置对象、全局变量加上注解,完善 MyPy 检查。
9. PEP 621 / PEP 517 / PEP 518 — 《打包与构建》
- PEP 517/518:引入
pyproject.toml统一项目配置。 - PEP 621:在
pyproject.toml中声明元信息(name、version、dependencies)。 - 学习:用 Poetry/Flit 体验现代打包流程,替代 legacy 的
setup.py。
10. PEP 20XX… 社区新兴实践
- PEP 703:去除 GIL(讨论中)
- PEP 615:时区支持
- PEP 657:精准错误行号
持续关注 Python 官方 Newsletter,了解最新 PEP 的落地与演进。
如何跟进这些 PEP
- 阅读原文:每个 PEP 都有背景、理念、示例。
- 写 Demo:对核心特性动手探索,64 行内写出最小可运行示例。
- 参与讨论:在
python-dev邮件列表、GitHub issue 留言,观察社区对特性的反馈。 - 升级实践:在新项目中尝试用到它们,逐渐用现代 Python 语法替代老写法。
通过“读 PEP → 写代码 → 贡献社区” 的闭环,对 Python 语法与社区演进的理解会越来越深入,也能更灵活地驾驭语言特性。
1 Python数据模型
Python是一个框架,数据模型是对框架的描述,规范语言自身各个组成部分的接口,确立序列、函数、迭代器、协程、类、上下文管理器部分行为
1.2 Python风格的纸牌
import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self,position):
return self._cards[position]
然后在终端输python看到返回下面的,再按书的内容输入即可(首先电脑里要安装了python)
Python 3.12.9 | packaged by Anaconda, Inc. | (main, Feb 6 2025, 18:49:16) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> **from Card import Card**
>>> beer_card = Card('7', 'diamonds')
>>> beer_card
Card(rank='7', suit='diamonds')
>>> **from Card import FrenchDeck **
>>> deck = FrenchDeck()
>>> len(deck)
52
>>> deck[0]
Card(rank='2', suit='spades')
>>> deck[-1]
Card(rank='A', suit='hearts')
>>> from random import choice
>>> choice(deck)
Card(rank='K', suit='spades')
>>> choice(deck)
Card(rank='6', suit='spades')
>>> choice(deck)
Card(rank='2', suit='spades')
>>> deck[:3]
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')]
>>> deck[12::13]
[Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]
>>> for card in deck:
... print(card)
...
Card(rank='2', suit='spades')
#后面省略了
排序
按规则,牌面大小按点数(A最大),黑桃(最大)、红心、方块、梅花(最小)的顺序排列
Card.py
import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self,position):
return self._cards[position]
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
@staticmethod
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(FrenchDeck.suit_values) + FrenchDeck.suit_values[card.suit]
python
Python 3.12.9 | packaged by Anaconda, Inc. | (main, Feb 6 2025, 18:49:16) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from Card import FrenchDeck
>>> deck = FrenchDeck()
>>> for card in sorted(deck, key=FrenchDeck.spades_high):
... print(card)
...
Card(rank='2', suit='clubs')
#后面省略了
1.3 模拟数值类型
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
元组
元组的作用:
1.作为不可变列表使用
2.用作没有字段名称的记录(类似于const的量)
元组拆包tuple unpacking
city, year, pop, chg, area = ('Tokyo', 2003, 32_450, 0.66, 8014)
复杂科研项目涉及到的高级、进阶python语法
面对一个涉及大量高级语法和复杂结构的项目,不熟悉是正常的。下面是高效学习和应对建议:
1. 不要焦虑,分块学习
- 你不需要一次性掌握所有内容。可以按需学习,遇到用到的再查。
- 先学会“查文档、查资料、问AI”,比死记硬背更重要。
2. 优先掌握核心基础
建议优先掌握这些内容(它们在项目中最常见):
- 面向对象编程(OOP):类、继承、抽象类、属性装饰器。
- 装饰器:理解
@的基本用法,先会用,后面再深入原理。 - 类型注解:会看懂函数参数和返回值的类型提示。
- 异常处理:try/except 的基本用法。
- 包和模块导入:会用 import,理解包结构。
- 常用第三方库:如 numpy、torch、cv2、PIL 的基本用法。
3. 遇到不会的,先查再问
- 遇到不懂的语法/函数/类,先用搜索引擎、ChatGPT、官方文档查一下。
- 不会的库/装饰器/类型注解,可以直接问我“xxx 是什么意思?怎么用?”我可以给你举例和解释。
4. 用“调试+实验”驱动学习
- 多用 print/断点/调试器,看变量、对象、函数的实际内容。
- 写小实验代码,比如单独写个装饰器、抽象类、类型注解的小例子跑一跑。
5. 善用 AI 辅助和代码补全
- 你可以随时把不懂的代码片段发给我,我可以帮你解释。
- 用 VSCode/PyCharm 的代码补全、跳转、文档提示功能,能大大降低理解难度。
6. 循序渐进,逐步深入
- 先保证能“用起来”,再慢慢“看懂原理”。
- 项目能跑起来、能改动一点点,就是进步。
- 随着用得多,理解会自然加深。
7. 推荐学习资源
- 廖雪峰Python教程(基础+进阶)
- Python官方文档
- Real Python(英文,进阶内容多)
- B站/YouTube 搜“Python 装饰器/抽象类/类型注解”等关键词
OVSG https://github.com/changhaonan/OVSG
这个项目涉及到不少高级/进阶的 Python 语法和编程范式**
1. 装饰器(Decorator)
- 例如
@hydra.main,用于自动注入配置参数。 - 项目中也可能有自定义装饰器(如抽象类的
@abc.abstractmethod)。
2. 抽象基类与多态
abc模块、ABC、@abstractmethod,如Chatter、EnvBase、Interpreter等。- 体现了面向对象的接口设计和多态。
3. 类继承与组合
- 各种基类(如
EnvBase、LLM、Interpreter)和子类(如NotionOVIDB、ChatGPTAPI、InterpreterXML)。 - 组合(如环境类组合数据库、推理器等)。
4. 类型注解(Type Hinting)
- 如
def chat(self, str_msg: str | list[any], ...) -> tuple[any, bool]: - 使用
typing、|(Python 3.10+)等。
5. 上下文管理器(with 语句)
- 处理文件、模型加载等资源管理。
6. 属性装饰器(@property)
- 如
@property def is_api(self): ...,实现只读/只写属性。
7. 元编程
- 动态导入、反射(如
getattr、setattr)、动态构建类/对象(如env_map[cfg.env_name](cfg))。
8. 函数式编程
- lambda、map、filter、sorted、key 函数等。
- 例如对 prompt 数据库的排序、相似度计算。
9. 异常处理
- try/except,尤其是与外部API(如OpenAI)交互时的重试机制。
10. 包与模块管理
- 多级包结构(如
ovsg.core.env),__init__.py的用法。 - 相对/绝对导入。
11. 配置管理与命令行参数
- 使用 Hydra/YAML 配置,支持多配置组合和命令行覆盖。
12. 数据结构与序列化
- 使用
pickle、json、xml.etree.ElementTree处理数据和任务描述。 - numpy、torch 等科学计算库的高阶用法。
13. 多线程/异步(可能涉及)
- 如果有大模型API调用或渲染,可能用到并发/异步。
14. 第三方库的高级用法
- 如 OpenAI API、Hydra、transformers、torch、cv2、PIL 等。
建议学习路径
- 面向对象编程(OOP):抽象类、继承、多态、组合、属性装饰器。
- 装饰器与元编程:理解装饰器、反射、动态对象创建。
- 类型注解与静态检查:熟悉 Python 3.10+ 的类型提示。
- 配置与命令行工具:掌握 Hydra、argparse、YAML 配置。
- 文件与数据结构处理:XML、JSON、Pickle、Numpy、Torch。
- 异常处理与上下文管理:资源安全与健壮性。
- 函数式编程:lambda、map、filter、sorted。
- 第三方库的进阶用法:如 transformers、OpenAI、cv2、PIL。
代码能力和工程管理能力
第一部分:心态篇 —— 像“软件工程师”一样思考
在学习任何具体工具之前,首先要转变三个核心观念:
1.从“一次性脚本”到“长期资产”:
- 旧观念: 科研代码只是为了跑出论文图表的脚本,能跑就行。
- 新观念: 您的代码库是您未来几年研究的核心资产。您今天写的代码,半年后的您需要能看懂、能修改、能扩展。正如综述中提到的“长期自主性”,您的代码也需要具备“长期可维护性”。
2.从“能跑就行”到“追求可复现”:
- 旧观念: 在我的电脑上能跑出结果就行了。
- 新观念: 我的代码必须保证在另一台干净的电脑上,也能通过简单的指令,复现出和论文中一模一样的结果。这是科学研究的黄金标准。
3.从“一锅乱炖”到“拥抱模块化”:
- 旧观念: 把所有逻辑都写在一个巨大的main.py里。
- 新观念: 将复杂的系统拆解成一个个功能内聚、接口清晰的“乐高积木”。综述中提到,高质量的开源求解器(如因子图库)极大地促进了SLAM的发展,这正是模块化力量的体现。
第二部分:战术篇 —— 必须掌握的工具与方法
基于上述心态,以下是您需要立刻开始学习和使用的具体技术。
代码能力 (Coding Skills):
-
版本控制 (Version Control) - git:
做什么: git不仅是备份工具。您需要学会使用分支 (branch) 功能。例如,为您论文#1的每个创新点(如“时序感知模块”)创建一个独立的分支feature/temporal_perception。在这个分支上开发、测试,完成后再合并回主分支。这能确保您的主分支永远是稳定可运行的。
如何达到: 学习并强制自己使用git branch, git checkout, git merge等命令。编写有意义的commit信息。 -
代码规范 (Code Style) - Linters & Formatters:
做什么: 安装并使用自动化代码格式化工具。Python用black和flake8,C++用clang-format。它们能自动将您的代码整理成统一的、易于阅读的风格。
如何达到: 在您的VS Code中安装对应的插件,并设置为保存时自动格式化。 -
调试技术 (Debugging) - IDE Debugger:
做什么: 告别print()调试。学习使用VS Code等IDE集成的图形化调试器。
如何达到: 学习如何在VS Code中为Python (pdb) 和 C++ (gdb) 配置launch.json。练习设置断点 (breakpoint),单步执行代码,观察变量的值和调用堆栈。这是“解剖”代码最强大的武器。
复杂工程管理能力 (Project Management Skills):
- 环境管理 (Environment Management) - Docker:
- 做什么: 将您整个项目(包括操作系统、所有系统库、所有Python包)封装到一个Dockerfile中。
- 如何达到: 学习Docker的基本概念(Image, Container, Dockerfile)。将您在“核心战壕”计划中手动配置环境的每一步,都翻译成Dockerfile中的一行指令。最终目标是,在新电脑上,只需一个docker build和一个docker run命令,就能完美复现您的完整开发环境。这对于保证您工作的可扩展性和在资源受限平台上的部署至关重要。
- 任务分解 (Task Decomposition) - TODO.md / GitHub Projects:
- 做什么: 将一个宏大的目标(如“完成论文#1”)分解成一系列具体的、可在一两天内完成的小任务。
- 如何达到: 在您的项目根目录下,创建一个TODO.md文件。将我们规划的“三个月冲刺计划”中的每一周任务,再细化到每一天。例如:
# TODO for Paper #1
## Week 5: Motion-Prediction-Assisted Segmentation
- [x] Research OpenCV optical flow functions.
- [x] Implement a simple script to propagate a mask from frame t-1 to t.
- [ ] Integrate this script into the SplaTAM perception loop.
每完成一项,就打一个勾。这能提供巨大的正反馈,并防止您迷失在宏大的目标中。
- 文档撰写 (Documentation) - README.md:
- 做什么: 将您的项目打造成一个别人(以及未来的您)能看懂、能使用的产品。
- 如何达到: 在项目初期,就认真撰写README.md。清晰地说明:这个项目是做什么的?如何安装依赖?如何运行代码来复现核心结果?一个清晰的文档是保证工作“可解释性和可用性”的第一步。
第三部分:实战篇 —— 在项目中刻意练习
Learn Python - scrimba
Access Control Scanner Challenge
https://scrimba.com/learn-python-c03
What is Scrimba
- Scrimba is an online platform for learning web development (HTML, CSS, JavaScript, React, etc.).
- Its distinguishing feature is the “scrim” — interactive screencasts where you can pause the video and edit the code in-place (i.e. the lesson itself is live/interactive) rather than purely watching a video then coding separately.
- It has free courses, plus a paid “Pro” subscription / career path offerings.
- According to G2 reviews, many users highlight that the interactivity (“pause and edit live code”) is a strong selling point.
- On Trustpilot, Scrimba has a score of ~4.2 / 5 with many positive reviews but some criticisms (especially pricing and occasional UI bugs)
Trustpilot - On Course Report, they show an average rating of ~4.43/5 for their bootcamp / course offerings.
Strengths
Based on user reviews, expert commentary, and feature descriptions, here are Scrimba’s strong points:
- Interactive Learning / Immediate Practice
The scrim approach means you don’t just passively watch code — you can immediately modify and test. This helps with retention and understanding. - Low friction to get started
Because everything is browser-based, and lessons are broken into short chunks (2–5 minute segments), it’s relatively easy to jump into and make incremental progress. - Quality Instruction & Content for Beginners
Especially for HTML/CSS and early JavaScript, many users find the explanations clear and well scaffolded. - Community & Support
Scrimba has a Discord / community presence, which helps learners ask questions, share projects, and stay motivated. - Transparent growth & legitimacy
The company has publicly shared metrics (e.g. ~500K users, ~$1.9M revenue in 2024) which suggests it's not some fly-by-night operation.
Weaknesses / Risks / Criticisms
Scrimba is not perfect. Here are the commonly noted drawbacks and risks:
- Editor / Platform Limitations
The in-browser editor is more basic than full desktop IDEs (e.g. lacking some advanced tooling). For advanced learners, this might feel limiting.
Some users report occasional UI bugs (e.g. the editor doesn’t refresh properly, or blocking parts of the view) and slowness or need to refresh. - Challenge Clarity
Some learners find that the challenge descriptions are vague or insufficiently guided, which leads to frustration. - Advanced / Depth Content
For more advanced topics or deep dives, some reviews feel the courses become more passive (less interactive) or don’t push you as hard.
Some users comment that the ROI diminishes after the beginner/ intermediate levels. - Pricing / Subscription Model
Some reviewers feel that the subscription cost is high relative to what’s offered, especially once free alternatives exist.
Others mention billing / cancellation issues (difficulty pausing or canceling) in older versions. - Dependence on Platform
Because your learning is tied to their environment, you may not get as much exposure to setting up your own dev environment, tooling, debugging workflows outside their sandbox. This could limit transition to “real-world” coding environments. - Inconsistent Course Quality
As with many platforms, not all courses/instructors are equally strong; some review authors point out that later courses are less polished.
- For absolute beginners or learners wanting interactive, fun onboarding: 8 / 10
- For more advanced learners wanting depth, tooling experience, or real-world workflows: 6.5–7 / 10
- As a career-path / job readiness program: somewhere in 7 / 10, assuming you supplement with real projects, external tooling, and extra practice beyond Scrimba’s scope.

浙公网安备 33010602011771号