欢迎光临
我们一直在努力

《流畅的Python》读书笔记01: 开启“流畅的Python”之旅

作者: andylin02 学习章节: 全书通览 关键词: 流畅的Python|Python进阶|数据模型|特殊方法|Pythonic|序列类型|一等函数|装饰器|迭代器|生成器|协程|元编程


一、前言

《流畅的Python》(Fluent Python)由巴西Python专家Luciano Ramalho所著,豆瓣评分高达9.4分,是Python进阶领域的必读经典。由奋战在Python开发一线近20年的Luciano Ramalho执笔,Victor Stinner、Alex Martelli等Python大咖担纲技术审稿人,从语言设计层面剖析编程细节,兼顾Python 3和Python 2,告诉你Python中不亲自动手实践就无法理解的语言陷阱成因和解决之道,教你写出风格地道的Python代码。2023年4月出版的第2版与时俱进,主体内容分为五部分:数据结构、函数即对象、类和协议、控制流、元编程。

很多人都经历了“Python基础语法掌握得差不多了,但写的代码量多了就会感觉土,不够地道”的困扰。《流畅的Python》正是这样一本能在代码实战层面带来质的飞跃的书,着重讲解Python语言所独有的功能,助你成功进阶为Python高手,教你充分利用Python特性,写出有效且现代的Python 3代码。

本文将通过详细的学习文档、读书笔记和总结,帮你系统了解这本书、掌握关键知识点,并结合源代码、架构图和流程图,助你建立知识体系框架。

二、本书讲了什么——全景概览

本书致力于帮助Python开发人员挖掘这门语言及相关程序库的优秀特性,避免重复劳动,同时写出简洁、流畅、易读、易维护,并且具有地道Python风格的代码。

全书共21章,分为六大部分(第2版为五部分):

全书思维导图框架

#mermaid-svg-7w8JoKbktZbL5IYS{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-7w8JoKbktZbL5IYS .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-7w8JoKbktZbL5IYS .error-icon{fill:#552222;}#mermaid-svg-7w8JoKbktZbL5IYS .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-7w8JoKbktZbL5IYS .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-7w8JoKbktZbL5IYS .marker{fill:#333333;stroke:#333333;}#mermaid-svg-7w8JoKbktZbL5IYS .marker.cross{stroke:#333333;}#mermaid-svg-7w8JoKbktZbL5IYS svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-7w8JoKbktZbL5IYS p{margin:0;}#mermaid-svg-7w8JoKbktZbL5IYS .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-7w8JoKbktZbL5IYS .cluster-label text{fill:#333;}#mermaid-svg-7w8JoKbktZbL5IYS .cluster-label span{color:#333;}#mermaid-svg-7w8JoKbktZbL5IYS .cluster-label span p{background-color:transparent;}#mermaid-svg-7w8JoKbktZbL5IYS .label text,#mermaid-svg-7w8JoKbktZbL5IYS span{fill:#333;color:#333;}#mermaid-svg-7w8JoKbktZbL5IYS .node rect,#mermaid-svg-7w8JoKbktZbL5IYS .node circle,#mermaid-svg-7w8JoKbktZbL5IYS .node ellipse,#mermaid-svg-7w8JoKbktZbL5IYS .node polygon,#mermaid-svg-7w8JoKbktZbL5IYS .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-7w8JoKbktZbL5IYS .rough-node .label text,#mermaid-svg-7w8JoKbktZbL5IYS .node .label text,#mermaid-svg-7w8JoKbktZbL5IYS .image-shape .label,#mermaid-svg-7w8JoKbktZbL5IYS .icon-shape .label{text-anchor:middle;}#mermaid-svg-7w8JoKbktZbL5IYS .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-7w8JoKbktZbL5IYS .rough-node .label,#mermaid-svg-7w8JoKbktZbL5IYS .node .label,#mermaid-svg-7w8JoKbktZbL5IYS .image-shape .label,#mermaid-svg-7w8JoKbktZbL5IYS .icon-shape .label{text-align:center;}#mermaid-svg-7w8JoKbktZbL5IYS .node.clickable{cursor:pointer;}#mermaid-svg-7w8JoKbktZbL5IYS .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-7w8JoKbktZbL5IYS .arrowheadPath{fill:#333333;}#mermaid-svg-7w8JoKbktZbL5IYS .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-7w8JoKbktZbL5IYS .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-7w8JoKbktZbL5IYS .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-7w8JoKbktZbL5IYS .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-7w8JoKbktZbL5IYS .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-7w8JoKbktZbL5IYS .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-7w8JoKbktZbL5IYS .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-7w8JoKbktZbL5IYS .cluster text{fill:#333;}#mermaid-svg-7w8JoKbktZbL5IYS .cluster span{color:#333;}#mermaid-svg-7w8JoKbktZbL5IYS div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-7w8JoKbktZbL5IYS .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-7w8JoKbktZbL5IYS rect.text{fill:none;stroke-width:0;}#mermaid-svg-7w8JoKbktZbL5IYS .icon-shape,#mermaid-svg-7w8JoKbktZbL5IYS .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-7w8JoKbktZbL5IYS .icon-shape p,#mermaid-svg-7w8JoKbktZbL5IYS .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-7w8JoKbktZbL5IYS .icon-shape .label rect,#mermaid-svg-7w8JoKbktZbL5IYS .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-7w8JoKbktZbL5IYS .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-7w8JoKbktZbL5IYS .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-7w8JoKbktZbL5IYS :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

《流畅的Python》全书结构

第一部分数据结构

第1章 Python数据模型

✓ 特殊方法(__getitem__, __len__, __repr__)✓ 模拟数值类型✓ 容器API

第2章 序列构成的数组

✓ 列表推导式与生成器表达式✓ 元组、切片、拆包✓ bisect、array、deque

第3章 字典和集合

✓ defaultdict, OrderedDict, Counter✓ __missing__方法✓ 散列表原理

第4章 文本和字节序列

✓ bytes与bytearray✓ Unicode规范化✓ 编解码器处理

第二部分把函数视作对象

第5章 一等函数

✓ 高阶函数✓ 参数注解✓ functools与operator模块

第6章 使用一等函数实现设计模式

✓ 策略模式重构✓ 命令模式

第7章 函数装饰器和闭包

✓ 装饰器执行时机✓ 变量作用域✓ nonlocal与闭包

第三部分面向对象惯用法

第8章 对象引用和垃圾回收

✓ 引用与可变性✓ 浅复制与深复制✓ 弱引用

第9章 符合Python风格的对象

✓ __slots__节省内存✓ @property与私有属性

第10章 序列的修改和切片

✓ 实现切片协议✓ 鸭子类型

第11章 接口与抽象基类

✓ 协议(Protocol)✓ __subclasshook__

第12章 继承的优缺点

✓ 方法解析顺序(MRO)✓ 多重继承风险

第13章 运算符重载

第四部分控制流程

第14章 可迭代对象与迭代器

✓ iter()函数✓ 生成器函数和表达式

第15章 上下文管理器

✓ with语句✓ contextlib与@contextmanager

第16章 协程

✓ .send()方法✓ yield from

第17章 期物处理并发

✓ concurrent.futures✓ 多线程vs多进程

第18章 asyncio并发

✓ 事件循环✓ 异步任务管理

第五部分元编程

第19章 动态属性与特性

✓ @property✓ 动态属性创建

第20章 属性描述符

✓ 描述符协议(__get__, __set__, __delete__)✓ 覆盖性vs非覆盖性描述符

第21章 类元编程

✓ 元类(metaclass)✓ __init_subclass__✓ 类装饰器

三、学好本书能学到哪些关键知识

1. 核心知识体系

知识模块具体内容学习价值
数据模型(核心底层) 特殊方法(__getitem__、__len__、__repr__、__str__、__bool__、__add__ 等) 理解 Python 解释器如何通过特殊方法实现对象操作,自定义类型拥有内置类型的能力
数据结构(内建数据工具箱) 列表推导式与生成器表达式(内存高效)、切片操作、bisect 二分法、array、deque、defaultdict、OrderedDict、Counter、Unicode 与字节序列处理 掌握所有 Python 序列和映射类型,优化数据访问效率
函数式编程(一等对象模型) 一等函数(赋值、传参、存储)、高阶函数(map、filter、reduce)、lambda、operator、functools.partial 写出更声明式、组合式、可复用的函数式代码
闭包与装饰器(函数增强) 变量作用域规则与 nonlocal 声明、闭包、装饰器原理与参数化装饰器、functools.wraps 理解运行时动态增强函数行为,写可插拔的扩展代码
面向对象惯用法(设计细节) 对象引用与可变性、浅复制与深复制、__slots__、@property、抽象基类与协议(鸭子类型)、多重继承与 MRO、运算符重载 写出“Pythonic”的类,正确管理内存和类设计
控制流程(异步与并发) 迭代器协议与生成器、yield 与生成器函数、yield from、协程与 .send()、asyncio 事件循环、concurrent.futures 线程/进程池 从同步思维进阶到协程与异步 IO,高并发落地
元编程(语言底层工具) @property 与特性、属性描述符协议(覆盖性 vs 非覆盖性)、__get__、__set__、__delete__、元类(type、__new__、__init__) 理解 Python 底层对象模型,构建高级框架与 ORM 等 DSL

2. 典型技术深度示例

  • obj[key] 的背后,Python 会调用 my_collection.__getitem__(key)。
  • len(my_object) 为什么不设计成 my_object.len()?背后的设计思想:内置类型可直接从 C 结构体读取长度(“抄近道”)而不调用任何方法,保证了效率;而对于自定义类型,len() 会触发对 __len__ 的调用,从而在效率和一致性之间取得平衡。
  • += 作用于元组内的可变元素时,可能同时抛出异常并改变对象——这种“诡异”行为正是理解可变性、引用和增量赋值的最好案例。
  • 生成器表达式能在处理笛卡尔积时省掉中间列表的巨大内存开销,用惰性求值实现百万级别组合的实时产出。

四、需要具备什么基础能力(前置知识)

学Python别一上来就啃《流畅的Python》,先搭好知识骨架,后面填内容才不散架。推荐的知识体系搭建路径如下:

必须掌握(低配版)

  • Python 基础语法(变量、数据类型、控制结构 if、for/while、函数定义与调用)
  • 基础数据结构:列表、元组、字典、集合的创建与基本增删改查,字符串常见操作
  • 类与对象基础:定义类、创建对象、实例属性、self、简单继承与方法重写
  • 异常处理基础:try/except 捕获异常

强烈推荐(高配版)

  • 迭代器与生成器概念(至少理解 for 循环如何工作,理解 yield 的基本用法)
  • 常用的高阶函数(map、filter、sorted)
  • 熟悉内置函数:repr、str、len、isinstance、getattr 等
  • 对 CPython 中“变量保存的是引用”有基本感知(按引用传递)

五、准备工作

5.1 开发环境搭建

  • Python 版本:推荐 Python 3.10 或更新版本(作者在 Python 3.10 中测试了示例,大部分在 3.9 和 3.8 也可运行)
  • 编辑器:PyCharm / VS Code(强烈建议插件:Python Docstring Generator, Pylance, Jupyter)
  • 交互式环境:预习/调试概念时建议用 Jupyter Notebook(支持边写边运行,便于验证代码片段)

5.2 必备资料清单

  • 实体书/电子书:《流畅的Python》(第2版),安道翻译,人民邮电出版社(2023年4月出版)
  • 官方代码仓库:访问 https://github.com/fluentpython/example-code-2e 获取第2版示例代码
  • 社区笔记与文章:CSDN、掘金、博客园的相关笔记文章
  • 延伸阅读:《Python Cookbook(第3版)》、《Python 参考手册(第4版)》

5.3 推荐学习时长与节奏

  • 全书600~736页,建议用 3~6个月 时间精读
  • 每周1章 + 配套代码实践 + 练习题,保持持续性输出
  • 从第14章(并发部分)开始,建议放慢节奏,配合项目实战

六、有什么注意事项

  • 基础不够硬,不要直接开刷。 这本书是面向想要精通 Python 3 的在职 Python 程序员的,主要为进阶人群设计。初学者需要先打好基础,否则容易被第一章的数据模型“劝退”。

  • 每一章都动手跑代码。 书里的示例代码与《流畅的Python》强关联,需要配合官方仓库同步运行。每个知识点最少得在本地跑通,再做一点变化,才能把“输入”变成“真正的理解”。

  • 从第1112章开始可能会变吃力,1618章(协程、asyncio)是最大难点。 很多读者反映读到抽象基类、多重继承 MRO、yield from/协程时难度飙升。建议这时放慢节奏,边读边画执行图/状态图,把每一条示例代码拆开打桩调试,遇到阻碍可以多看几个不同角度的博客作补充(例如先看理解闭包,再看装饰器参数化)。

  • 不要只记不输出。 记住这本书的核心价值是“写出地道Pythonic代码”,而不仅仅是掌握了一大堆特殊方法的名字。每天或每周写总结、提炼章节小结,可以参照作者每章的小结进行回顾。

  • 英文好的推荐对照原版阅读。 中文版翻译质量虽高,但某些抽象概念(如混入、组合、委托、元类的用途)可能不够直观。英文原版便于查阅术语和原始作者的表述。

  • 不必一次性强行刷到底。 本书厚达600多页,可以按“数据结构→函数/装饰器→并发→元编程”作为主线,把元编程部分放到最后攻坚。在学习协程/并发的时候,强烈建议做一个小型的asyncio爬虫demo来加深印象。

  • 七、详细学习文档与读书笔记(章节提炼)

    以下是21章的核心知识提炼,建议配合代码仓库对照复习。

    章标题核心知识点难度代码关键点
    1 Python 数据模型 特殊方法(__len__、__getitem__、__repr__/__str__、__bool__),数据模型 vs 对象模型,len() 的设计哲学 ⭐⭐⭐ FrenchDeck 类实现一副牌,可迭代、支持 len() 和索引
    2 序列构成的数组 列表推导和生成器表达式(内存效率)、元组拆包、namedtuple、切片原理、+/*/+= 陷阱、bisect、array、memoryview、deque ⭐⭐ 笛卡尔积生成器 vs 列表推导;+= 陷阱(碰可变 vs 不可变)
    3 字典和集合 字典推导、defaultdict、OrderedDict、ChainMap、Counter、__missing__、UserDict、不可变映射、集合运算、散列表实现原理 ⭐⭐ defaultdict(list) 自动分组;__missing__ 实现“键不存在时的默认行为”
    4 文本和字节序列 bytes/bytearray、编解码器(utf-8等)、UnicodeEncodeError/UnicodeDecodeError处理、unicodedata规范化、文本文件处理、双模式 API ⭐⭐⭐ 读二进制文件;规范化用户输入(NFC/NFKD + casefold)
    5 一等函数 函数也是对象、高阶函数(map、filter、reduce)、lambda、operator、functools.partial、参数注解、callable() ⭐⭐ 用 partial 锁定函数参数减少重复传参
    6 使用一等函数实现设计模式 用一等函数/可调用对象取代传统“函数类”实现策略模式、命令模式 ⭐⭐ 策略模式:存储函数字典,而非每种策略一个类
    7 函数装饰器和闭包 装饰器执行时机(导入时)、变量作用域 LEGB、闭包机制、nonlocal、参数化装饰器、functools.wraps ⭐⭐⭐⭐ 注册装饰器;计时器装饰器;带参数的装饰器(两层嵌套)
    8 对象引用、可变性和垃圾回收 变量是引用、is/==区别、浅复制 vs 深复制、垃圾回收与 __del__、弱引用(weakref) ⭐⭐⭐ 观察可变对象作为默认参数引起的灾难,改用 None
    9 符合Python风格的对象 __slots__ 节省内存、@property 创建特性、私有属性与 __name mangling、对象格式化 ⭐⭐ Vector 类:展示属性可读/可写设计
    10 序列的修改、散列和切片 实现 __getitem__/__setitem__/__delitem__ 支持序列协议,实现 __hash__/__eq__ 使对象可散列,实现切片支持 ⭐⭐⭐⭐ Vector 支持切片并返回新 Vector
    11 接口:从协议到抽象基类 鸭子类型与协议、抽象基类(abc)、__subclasshook__、isinstance vs 协议、collections.abc ⭐⭐⭐⭐ 实现 __len__/__getitem__ 让类满足 Sized 和 Sequence 协议
    12 继承的优缺点 __mro__(方法解析顺序)、多重继承粒度与“钻石继承”问题、super()、mixins ⭐⭐⭐⭐ 按需混入职责,不滥用多重继承
    13 正确重载运算符 __add__、__mul__、反向运算符(__radd__),增量赋值运算符(__iadd__),一元运算符 ⭐⭐⭐ 实现向量的加法、标量乘法等重载
    14 可迭代对象、迭代器和生成器 可迭代协议(__iter__),迭代器协议(__next__),生成器函数(yield)、生成器表达式、itertools 实用工具 ⭐⭐⭐⭐ 实现等差数列生成器,惰性求值
    15 上下文管理器和else块 with 语句工作原理,__enter__/__exit__,contextlib 与 @contextmanager,for…else/while…else ⭐⭐⭐ 用上下文管理器自动管理资源和事务提交/回滚;用 @contextmanager 简化写法
    16 协程 生成器演化成协程:.send(value)、.throw()、.close()、yield from、协程返回值、async/await ⭐⭐⭐⭐⭐ 通过 yield from 委派任务;简易协程模拟计算器
    17 使用期物处理并发 concurrent.futures 模块(ThreadPoolExecutor/ProcessPoolExecutor),多线程 vs 多进程,GIL 相关 ⭐⭐⭐ 并下载多张图片,对比多线程与多进程性能
    18 使用asyncio包处理并发 协程驱动的事件循环,asyncio 任务创建与等待,锁/队列/信号量,同步原语 ⭐⭐⭐⭐⭐ 异步 HTTP 请求,多任务并发与顺序执行对比
    19 动态属性和特性 @property(特性)、属性工厂、动态属性(__getattr__)、__setattr__ 行为 ⭐⭐⭐ LazyProperty 实现缓存计算结果;特性验证赋值
    20 属性描述符 覆盖性与非覆盖性描述符协议(__get__、__set__、__delete__)、描述符用法、实例级 vs 类级存储 ⭐⭐⭐⭐ 自定义验证描述符(如 @Positive)
    21 类元编程 元类:type 本质,__new__/__init__ 在类创建时的角色,__init_subclass__、类装饰器 ⭐⭐⭐⭐⭐⭐ 一个简单的 ORM 模型生成器(元类拦截类属性生成表映射)

    难度说明:⭐ 最容易 → ⭐⭐⭐⭐⭐⭐ 最难(元编程依然是绝大部分 Python 开发者的天花板)

    关键代码演示

    下面选取第一章最具代表性的“Python风格的纸牌”示例,展示数据模型的力量:

    import collections
    from random import choice

    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]

    if __name__ == '__main__':
    deck = FrenchDeck()
    print(f"牌库共有: {len(deck)} 张")
    print(f"访问第一张牌: {deck[0]}")
    print(f"访问最后一张牌: {deck[1]}")
    print("随机抽取一张牌:", choice(deck))
    print("\\n前 15 张牌:")
    for card in deck[:15]:
    print(card)

    代码运行输出

    牌库共有: 52 张
    访问第一张牌: Card(rank='2', suit='spades')
    访问最后一张牌: Card(rank='A', suit='hearts')
    随机抽取一张牌: Card(rank='Q', suit='diamonds')

    前 15 张牌:
    Card(rank='2', suit='spades')
    Card(rank='3', suit='spades')
    Card(rank='4', suit='spades')
    Card(rank='5', suit='spades')
    Card(rank='6', suit='spades')
    Card(rank='7', suit='spades')
    Card(rank='8', suit='spades')
    Card(rank='9', suit='spades')
    Card(rank='10', suit='spades')
    Card(rank='J', suit='spades')
    Card(rank='Q', suit='spades')
    Card(rank='K', suit='spades')
    Card(rank='A', suit='spades')
    Card(rank='2', suit='diamonds')
    Card(rank='3', suit='diamonds')

    这段代码的亮点:虽然 FrenchDeck 没有显式继承任何序列/迭代基类,仅实现了 __len__ 和 __getitem__,Python 解释器就能自动为它赋予 len() 函数、切片操作、for…in 迭代甚至 random.choice() 的完整序列风采—这就是 Python 数据模型的神奇所在。

    八、《流畅的Python》第一章详细展开(预告)

    按照你提到的 blog 风格,我们来提前解析第一章的最重要部分。

    1.1 本章核心

    第一章是整本书的“哲学入口”,核心回答两个问题:

  • 什么是 Python 的数据模型? 数据模型其实就是对 Python 框架的描述,它规范了序列、迭代器、函数、生成器、协程、类和上下文管理器等组成部分的接口,为编写最地道的 Python 代码提供 API 支撑。

  • “Python 风格”从何而来? “Pythonic” 的源泉就是数据模型——它通过“特殊方法”为框架与用户代码之间建立沟通桥梁,让我们自定义的对象能和内置对象一样与语言特性无缝集成。

  • 1.2 核心议题:特殊方法(魔术方法)

    特殊方法是让自定义类型具备内置类型行为的关键,名字以 __ 开头和结尾(如 __getitem__),在满足特殊句法(如 obj[key])时会被解释器自动调用。我们通常不直接调用特殊方法,而是通过 len(my_obj)、my_obj[key]、str(my_obj) 等触发解释器去调用。

    推荐实现:

    • __repr__:主要在交互式控制台下打印对象,或用于调试/记录日志时,给出“开发者友好”的详细表示(往往可以包含复原对象的表达式)。如果未实现它,打印对象时会退化为 <A object at 0x000>。
    • __str__:调用 str() 或在字符串格式化中使用 %s 时触发,用于提供“用户友好”的简洁描述。如果没有实现 __str__,解释器会在 __str__ 缺失时回退调用 __repr__。
    • __bool__:自定义对象的真假判断,or / and / if / while 判定时会用到。
    • __add__、__mul__:分别与 + 和 * 运算符绑定(对数值类型等实现运算符重载)。

    1.3 为什么不将 len 设计成普通方法

    本书反复强调的一条原则:len(collection) 而不是 collection.len(),是为了在“内置类型性能”和“语言一致性”之间达到完美平衡。对于内置类型(如列表、字符串、字典),解释器直接从 C 结构体中读取 ob_size 字段获取长度,不调用任何 Python 方法,效率远高于普通方法调用;而对于用户自定义的类,len(collection) 会自动调用其 __len__ 方法,保持了行为的统一。

    这背后正是“Python之禅”(运行 import this 可看到)中的原则:“不能让特例特殊到开始破坏既定的规则”。

    1.4 “一摞Python风格的纸牌”——一个完整的实现和测试

    [完整实现见上文第七章的代码以及运行输出,此处直接引用。]

    九、知识体系图:从底层到应用全景

    #mermaid-svg-agpCxQDPbeII8ZX7{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-agpCxQDPbeII8ZX7 .error-icon{fill:#552222;}#mermaid-svg-agpCxQDPbeII8ZX7 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-agpCxQDPbeII8ZX7 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-agpCxQDPbeII8ZX7 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-agpCxQDPbeII8ZX7 .marker.cross{stroke:#333333;}#mermaid-svg-agpCxQDPbeII8ZX7 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-agpCxQDPbeII8ZX7 p{margin:0;}#mermaid-svg-agpCxQDPbeII8ZX7 .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster-label text{fill:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster-label span{color:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster-label span p{background-color:transparent;}#mermaid-svg-agpCxQDPbeII8ZX7 .label text,#mermaid-svg-agpCxQDPbeII8ZX7 span{fill:#333;color:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 .node rect,#mermaid-svg-agpCxQDPbeII8ZX7 .node circle,#mermaid-svg-agpCxQDPbeII8ZX7 .node ellipse,#mermaid-svg-agpCxQDPbeII8ZX7 .node polygon,#mermaid-svg-agpCxQDPbeII8ZX7 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-agpCxQDPbeII8ZX7 .rough-node .label text,#mermaid-svg-agpCxQDPbeII8ZX7 .node .label text,#mermaid-svg-agpCxQDPbeII8ZX7 .image-shape .label,#mermaid-svg-agpCxQDPbeII8ZX7 .icon-shape .label{text-anchor:middle;}#mermaid-svg-agpCxQDPbeII8ZX7 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-agpCxQDPbeII8ZX7 .rough-node .label,#mermaid-svg-agpCxQDPbeII8ZX7 .node .label,#mermaid-svg-agpCxQDPbeII8ZX7 .image-shape .label,#mermaid-svg-agpCxQDPbeII8ZX7 .icon-shape .label{text-align:center;}#mermaid-svg-agpCxQDPbeII8ZX7 .node.clickable{cursor:pointer;}#mermaid-svg-agpCxQDPbeII8ZX7 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-agpCxQDPbeII8ZX7 .arrowheadPath{fill:#333333;}#mermaid-svg-agpCxQDPbeII8ZX7 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-agpCxQDPbeII8ZX7 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-agpCxQDPbeII8ZX7 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-agpCxQDPbeII8ZX7 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-agpCxQDPbeII8ZX7 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-agpCxQDPbeII8ZX7 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster text{fill:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 .cluster span{color:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-agpCxQDPbeII8ZX7 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-agpCxQDPbeII8ZX7 rect.text{fill:none;stroke-width:0;}#mermaid-svg-agpCxQDPbeII8ZX7 .icon-shape,#mermaid-svg-agpCxQDPbeII8ZX7 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-agpCxQDPbeII8ZX7 .icon-shape p,#mermaid-svg-agpCxQDPbeII8ZX7 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-agpCxQDPbeII8ZX7 .icon-shape .label rect,#mermaid-svg-agpCxQDPbeII8ZX7 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-agpCxQDPbeII8ZX7 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-agpCxQDPbeII8ZX7 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-agpCxQDPbeII8ZX7 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

    Pythonic 代码

    Python 数据模型 核心

    特殊方法/魔术方法

    序列协议__len__, __getitem__, __setitem__…

    数值协议__add__, __mul__, __radd__…

    迭代/上下文协议__iter__, __next__, __enter__, __exit__

    属性机制__getattr__, __setattr__, __getattribute__

    内建序列list, tuple, str, dict, set

    自定义序列如FrenchDeck

    运算符重载

    生成器/yield

    asyncio协程

    描述符协议

    特性property

    元编程体系元类/动态类创建

    十、本书学习总结

    《流畅的Python》是 Python 进阶之路上不可绕过的一本里程碑式著作,它所提炼的核心知识体系包括以下几大层级。

    第一层(第一章~第四章):扎实掌握 Python 的数据模型和内置数据结构(序列/字典/集合/字符和字节序列),是所有进阶代码的地基。

    第二层(第五章~第七章):从“函数是一等对象”出发,理解闭包和装饰器是构造灵活 API 和横切关注点(日志、缓存、权限等)的利器;“使用一等函数简化设计模式”则直接提升代码的抽象与复用能力。

    第三层(第八章~第十三章):面向对象的高级话题,包括对象引用与垃圾回收、__slots__ 优化、@property、序列对象的切片/散列/修改、抽象基类与动态协议、多重继承(__mro__)以及运算符重载。这部分与编写类库 / 框架高度相关。

    第四层(第十四章~第十八章):从迭代器/生成器出发,到协程与 asyncio 异步并发编程,一次性打通 Python 的惰性求值与高性能 IO 的知识缺口。

    第五层(第十九章~第二十一章):元编程——特性、属性描述符、元类——这最终让开发者能写出和框架(Django/SQLAlchemy 等)一样强大的底层工具。

    学好本书不仅仅是学会了如何用 Python 写出漂亮、可读、专业的代码,更重要的是能用 Python 的独特视角重新理解编程语言的设计哲学,实现从“会写 Python”到“写出 Pythonic 代码”的质变。

    祝你在探索《流畅的Python》的道路上先苦后甜,不断收获编码的深刻乐趣!


    本文为个人学习笔记,仅用于知识分享。如有错误,欢迎指正。 👍🏻 点赞 + 收藏 + 分享,让更多开发者看到这篇深度解析!❤️ 如果觉得有用,请给个赞支持一下作者!

    赞(0)
    未经允许不得转载:171主机测评 » 《流畅的Python》读书笔记01: 开启“流畅的Python”之旅
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址